How to use named area in my model for an array of elements?

I know that I can make a request for the latest books based on an array, as in

scope :recent_books, lambda {|since_dt| {:conditions=>{:created_at >= since_dt}}}

but how can I do a similar query when I have an array of elements, for example. what if I want to know if there are records matching dates in the array [date1, date2, date3, etc.]

I think there should be a collect / inject / select / map y method that will do this, but I'm not sure what to read them.

+6
source share
2 answers

If you pass an array as a value, ActiveRecord is smart enough to compare its inclusion in the array. For instance,

 Book.where(:author_id => [1, 7, 42]) 

creates an SQL query with a WHERE similar to:

 WHERE "author_id" IN (1, 7, 42) 

You can use this in scope just as you would set normal conditions:

 class Book < .... # Rails 3 scope :by_author, lambda { |author_id| where(:author_id => author_id) } # Rails 2 named_scope :by_author, lambda { |author_id { :conditions => {:author_id => author_id} } } end 

Then you can pass a single ID or an array of identifiers to by_author and it will work:

 Book.by_author([1,7,42]) 
+16
source

In Rails 4, I can verify that a string is included in an array attribute using an area like this:

 scope :news, -> { where(:categories => '{news}') } 

Or with an argument:

 scope :by_category, ->(category) { where(:categories => "{#{category}}") } 
+4
source

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


All Articles