如何在我的模型中针对一组项目使用命名范围? [英] How can I use a named scope in my model against an array of items?

查看:25
本文介绍了如何在我的模型中针对一组项目使用命名范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以根据数组查询最近的书籍

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.]

我认为必须有一个 collect/inject/select/map y 方法可以做到这一点,但我不确定阅读它们的方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆