2017-03-01 51 views
0

以下代码给出了一个空的范围。 Category_ids是一个类别数组。如何为数组创建范围?

scope :art, ->{ where(:category_ids => '1') } 

如何检查数组中是否存在其中一个类别?

+0

你在用什么数据库? Postgres/MySQL/...? –

回答

0
  1. 得到类别
  2. 纠正你在那里查询

例子:

has_many :categories 
scope :art, -> { required = [Category.first]; where(categories: required) } 

我认为在你的模型,你有categories关联。在这种情况下,您可以在where查询中使用categories: requiredrequired应该设置为你想要的类别数组

0

你说category_ids是一个类别数组(我假设类别ID的)。你是否试图返回所有具有该数组中的类别ID的记录?如果是这样,你正在寻找:

scope :art, -> { where (:category_id => category_ids) } 

或者与新的Ruby语法:

scope :art, -> { where(category_id: category_ids) } 

如果我误解,你正在寻找为1的类ID的任何记录,那么你正在寻找:

scope :art, -> { where(category_id: '1') }