Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3: combine scope with OR

I need to combine name scope with or operator... Something like:

class Product < ActiveRecord::Base
  belongs_to :client

  scope :name_a, where("products.name = 'a'")
  scope :client_b, joins(:client).where("clients.name = 'b'")

  scope :name_a_or_b, name_a.or(client_b)  
end

Thx

like image 452
Pioz Avatar asked Aug 23 '10 14:08

Pioz


1 Answers

From Arel documentation

The OR operator is not yet supported. It will work like this: users.where(users[:name].eq('bob').or(users[:age].lt(25)))

This RailsCast shows you how to use the .or operator. However, it works with Arel objects while you have instances of ActiveRecord::Relation. You can convert a relation to Arel using Product.name_a.arel, but now you have to figure out how to merge the conditions.

like image 159
Simone Carletti Avatar answered Sep 26 '22 03:09

Simone Carletti