Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do a Rails 3 select IN using where clauses

Tags:

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) 
like image 387
Bob Benedict Avatar asked Jun 07 '11 03:06

Bob Benedict


People also ask

What does where return rails?

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 in Ruby on Rails?

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.


2 Answers

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) 
like image 149
opsb Avatar answered Oct 02 '22 13:10

opsb


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]}) 
like image 22
Mischa Avatar answered Oct 02 '22 11:10

Mischa