如何在模型中对项目数组使用命名作用域? [英] How can I use a named scope in my model against an array of items?
问题描述
我知道我可以像这样在数组中查询最近的书
I know that I can do a query for recent books based on an array as in
scope :recent_books, lambda {|since_dt| {:conditions=>{:created_at >= since_dt}}}
但是当我有一系列项目(例如,如果我想知道是否有与[date1,date2,date3等]数组中的日期匹配的记录,怎么办?
but how can I do a similar query when I have an array of items, e.g. what if I want to know if there any records that match the dates in an array of [date1, date2, date3, etc.]
我认为必须有一个收集/注入/选择/映射方法,但我不确定从阅读它们中会得到什么.
I think there must be a collect/inject/select/map y method that'll do it but I am not sure which from reading them.
推荐答案
如果将数组作为值传递,则ActiveRecord足够聪明以进行比较以包含在数组中.例如,
If you pass an array as the value, ActiveRecord is smart enough to compare for inclusion in the array. For example,
Book.where(:author_id => [1, 7, 42])
生成带有WHERE
子句的SQL查询,类似于:
produces a SQL query with a WHERE
clause similar to:
WHERE "author_id" IN (1, 7, 42)
您可以像设置正常条件一样,以scope
的方式利用此优势:
You can take advantage of this in a scope
the same way 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
然后,您可以将单个ID或ID数组传递给by_author
,它将正常工作:
Then you can pass a single ID or an array of IDs to by_author
and it will just work:
Book.by_author([1,7,42])
这篇关于如何在模型中对项目数组使用命名作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!