I am using Rails 3 and I need to do a select where the primary key of the records is IN a resulting previous select. You can do this easily using straight SQL using an IN. Here is the obviously incorrect way I have done what I need. What's the Rails way to do this well:
@task = Link.find(params[:id]) clients = Client.where('task_id = ?',@task.id).select('DISTINCT(company_id)') company_list = [] clients.each do |client| company_ids << client.company_id end @companies = Company.where(:id => company_ids)
where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
As others have mentioned I'd use join in this case. The syntax for using "in" is also very simple though e.g.
company_ids = [1,2,3,4] @companies = Company.where("id in (?)", company_ids)
Update
Actually it's even simpler than that now (I think rails 3+), you can do
company_ids = [1,2,3,4] @companies = Company.where(id: company_ids)
This does not answer your question about "select IN using where clauses", but I think your whole script can be rewritten in one line using joins
. This should give the same result as your snippet above:
@companies = Company.joins(:clients).where(:clients => {:task_id => params[:id]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With