How can I use a named scope in my model against an array of items?

风流意气都作罢 提交于 2019-11-30 20:39:31

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

produces a SQL query with a WHERE clause similar to:

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

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

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

In Rails 4, I can check for the inclusion of a string in an array attribute by using a scope like this:

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

Or with an argument:

scope :by_category, ->(category) { where(:categories => "{#{category}}") }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!