I’m trying to create a Rails 3 model scope, which is, essentially:
scope :published, where(:published => true)
scope :viewable_by, lambda { |user| where(:user_id => user.id).or(published) }
The trouble is, I can’t find a way to make this work.
I had hoped arel_table would work, but it complains it “Cannot visit ActiveRecord::Relation”:
where(arel_table[:user_id].eq(user.id)).or(published)
This could be done by replicating the “published” scope as Arel but then I would be repeating code (and in my project the “published” scope is quite a bit more in depth).
The best I can come up with is this:
scope :viewable_by, lambda { |user| where("(user_id = ?) OR (#{published.where_values.collect(&:to_sql).join(" AND ")})", user.id) }
This is the shortest I could come up with after a bit of digging around:
(Of course it only works with a single where clause; use a
joinif there’s more than one.)I would recommend using a gem like MetaWhere that more clearly exposes some of the Arel underpinnings. Here’s an example from the main page linked above that creates an OR query: