Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord query

I have two models Project and UrlList. A project :has_many url_list and a url_list :belongs_to project.

Now I have array for project id's all_projects = [1,2,5,8,16]. I want to retrieve all the records from url_list where project_id is one of those from all_projects array. How do I write code for it?

like image 237
Bhushan Lodha Avatar asked Feb 21 '23 17:02

Bhushan Lodha


1 Answers

You can pass an array as value for an attribute to where method:

all_projects = [1, 2, 5, 8, 16]   
url_lists = UrlList.where(:project_id => all_projects)

It'll generate SQL query like that:

SELECT `url_lists`.* FROM `url_lists` WHERE `project_id`.`user_id` IN (1, 2, 5, 8, 16)
like image 141
KL-7 Avatar answered Mar 07 '23 00:03

KL-7