以下代码给出了一个空的范围。 Category_ids
是一个类别数组。如何为数组创建范围?
scope :art, ->{ where(:category_ids => '1') }
如何检查数组中是否存在其中一个类别?
以下代码给出了一个空的范围。 Category_ids
是一个类别数组。如何为数组创建范围?
scope :art, ->{ where(:category_ids => '1') }
如何检查数组中是否存在其中一个类别?
如果你使用Postgres的你可以使用这种方法:https://www.viget.com/articles/searching-serialized-fields-in-rails-using-postgres-arrays
例子:
has_many :categories
scope :art, -> { required = [Category.first]; where(categories: required) }
我认为在你的模型,你有categories
关联。在这种情况下,您可以在where查询中使用categories: required
。 required
应该设置为你想要的类别数组
你说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') }
你在用什么数据库? Postgres/MySQL/...? –