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

Bob Benedict picture Bob Benedict · Jun 7, 2011 · Viewed 19.1k times · Source

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)

Answer

opsb picture opsb · Nov 1, 2012

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)