Rails controller match one var to another var - ruby-on-rails

I have a table that has alot of data inside it
I'm wanting to do something like this. To grab everything inside a column that matches something else inside another column in another table.
So #car = Cardata.find_by(#carmake)
So, #carmake will be volvo, Typed in a separate form and stored in a table.
In the table Cardata there is a massive list (about 40k records) with different cars ranging from ford to renault to volvo.
The question is. Would #car display all the records that have the word volvo inside?? Or is it the wrong way of doing this? or do i need to label it by column?
Sam

To get all of them:
#cars = Cardata.where(carmake: #carmake).all
To get just the first:
#car = Cardata.where(carmake: #carmake).first

you should be doing:
#car = Cardata.find_by_attribute_name(#carmake) # This will return the first car that matches #carmake.
Assuming attribute_name is model.
You'd do:
Cardata.find_by_model(#carmake)
If you want all the cars that matches #carmake.
You need to do:
Cardata.where(model: #carmake) # this will return an array of all cars with model #carmake.

Assuming you have a column in car data for make, I think you'd want to do something like:
#cars = Cardata.where(make: #carmake).all

Related

Ruby on Rails controller order with strings

So I'm trying to organize one of my views so that the articles of my website are listed by the name of the title. For example some of my articles are named "article pt.1, history pt.2, society pt.1, etc". I do have them sorted correctly using this line of code in the Articles controller
def index
#articles = Article.order(:user_id)
end
It does work using the user id, but if I wanted to add another category and have them in alphabetical order, I would need to update the user id of each article which is not practical as they number a little over 200 in the database. What I would like to is somehow take a partial of the article title and sort each one like I am with the user_id field. This way I can sort each one using the string partial such as "article" from "article pt.1"
Thank you for reading and have a wonderful day!
Why not just sort by the title? Assuming you have a column in your articles table called title:
For alphabetical order
def index
#articles = Article.order(:title)
end
For reverse alphabetical order
def index
#articles = Article.order(title: :desc)
end
If you really want to just sort by a substring of the title. You'll have to add a new column to the articles table (called slug in this example):
rails g migration AddSlugToArticles slug:text
rails db:migrate
Then you'll have to update the slug field of every record
Article.all.each do |article|
new_slug = #your code to generate substring here
article.update(slug: my_string
end
then order by slug:
def index
#articles = Article.order(:slug)
end
First of all, it is not very clear about the output that you want, but based on assumption and the description mentioned in the post, it seems like you want to sort the string field not based on whole value but based on substring.
It is better to use the order to get the strings alphabetically sorted.
#articles = Article.order(:title)
And it will also serve the purpose as it will first match the first alphabet of each string and also handle null values at the same time.
Why write a custom logic if the purpose is fulfilled by an already defined method.
I was able to do it using the sort function instead of order using the :title field on the articles controller.
def index
#articles = Article.sort(:title)
end

Rails: finding records where attribute includes some value

I have a "Stores" model that contains various locations. Among the attributes for each store is the the "brands" that is carries.
Example: Store1, brands: "Nike, Adidas, Polo"; Store2, brands: "Jcrew, Polo"
I want to be able to select all stores where brand contains "Adidas" (may also contain other brands)
Something along the lines of:
#search = Stores.where(brands: params[:brand])
but need it to be
#search = Stores.where(brands.include? params[:brand])
which clearly doesn't work
What's the best way to deal with this?
If brands is a string and params[:brand] contains a single brand name, you can use MySQL's LIKE function:
#search = Stores.where(['BRANDS LIKE ?', "%#{params[:brand]}%"])
You can do this with the following statement.
#search = Stores.where("brands = ?", params[:brand])
A similar example is given in Listing 11.43 of the Hardtl rails tutorial
You should also note that rails models generally are meant to have singular names, i.e. Store instead of Stores.

How to show all departments where school name = x?

Upon the creation of a department, users have the option to add the name of a school. On the show page of the school, I want to show all the departments with the school of that name.
My school controller's show action looks like this:
def show
#department = Department.where(:school == 'university of connecticut')
end
This obviously isn't working. What is the correct syntax for this?
Either if these should give you the expected results:
#department = Department.where(school: 'university of connecticut').first
or
#department = Department.where('school = ?', 'university of connecticut').first
where takes either a hash or a SQL statement. Note that in the first example, we're using the shortcut hash method when using a symbol symbol: value, which is equivalent to :symbol => value
Also, keep in mind that where returns an ActiveRecord::Relation object, not an ActiveRecord object. You'll need to add .first or another form of .find if you wish to receive an ActiveRecord object directly.
You're close:
Department.where(school: 'university of connecticut').first
i.e. normal hash syntax.

Ruby on Rails: where returning nil

In my app I'm obtaining a certain category, and I'm filtering the associated items based on their name.
The following code should be pretty clear:
categories = Category.where(:id => params[:category_id]).includes(:items).where("lower(items.name) like ?", "%#{params[:keywords].downcase}%")
However, if the name filter excludes all the items, the categories object returned by where is nil. Is this the expected behaviour? How can I get the category even either items exist or not?
The easiest way might be to just split the query:
#category = Category.find(params[:category_id])
#items = #category.items.where("lower(items.name) like ?", "%#{params[:keywords].downcase}%")
Based on your code it seems like category_id references only 1 category so I've changed it to singular.
You should look into doing an OUTER JOIN against the items table which will give you categories regardless of whether or not their items meet the name filter.

Sorting and searching on a field which model doesn't have

I have an HTML table where I show the data from a particular model but I also show a column in the HTML table which doesn't belongs to that model. this column comes after some calculation(In this calculation I use 3-4 more tables). I want to give the sorting and searching functionality on that column. Anyone having idea what is the best way to do that?
Updated:
The main problem is if I provide sorting/searching on that column then I have to fetch all records from database for calculation which will not be good idea.
If you are looking for performance solution: just add new field into your table to store your calculation.
Anyway, you can't solve your problem without fetching all your records.
Or you can use JavaScript for searching and sorting, but only if there are not many items.
You can sort you model:
q_new.sort! { |x, y|
y.creation_date <=> x.creation_date
}
creation_date is a any field or a method of the model.
I would create a virtual resource on the model, which contains the sorter in Ruby-code. Assuming sum is your virtual property.
def by_sum(options = {})
#items = self.class.find(options)
#items.sort! { |a,b| a.sum <=> b.sum }
end
In your controller you can call:
Item.by_sum({:where => "'foo' = 'bar'"})

Resources