ActiveRecord Request

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

Now I have an array for the project id all_projects = [1,2,5,8,16] . I want to get all the entries from url_list , where project_id is one of the arrays from the all_projects array. How to write code for this?

+4
source share
1 answer

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

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

It will generate an SQL query as follows:

 SELECT `url_lists`.* FROM `url_lists` WHERE `project_id`.`user_id` IN (1, 2, 5, 8, 16) 
+8
source

Source: https://habr.com/ru/post/1392674/


All Articles