2010-08-23 28 views
10

我需要的名稱與範圍或經營相結合...... 喜歡的東西:Rails3中:用結合範圍或

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

回答

9

Arel documentation

OR算不算但支持。它的工作是這樣的: users.where(users[:name].eq('bob').or(users[:age].lt(25)))

This RailsCast展示瞭如何使用.or操作。但是,它可以與Arel對象一起使用,而您有ActiveRecord::Relation的實例。 您可以使用Product.name_a.arel將關係轉換爲Arel,但現在您必須弄清楚如何合併條件。

8

繼承人一個黑客,我會用對付失蹤的特點:

class Product < ActiveRecord::Base 
    belongs_to :client 

    class << self 
    def name_a 
     where("products.name = 'a'") 
    end 

    def client_b 
     joins(:client).where("clients.name = 'b'") 
    end 

    def name_a_or_b 
     clauses = [name_a, client_b].map do |relation| 
     clause = relation.arel.where_clauses.map { |clause| "(#{clause})" }.join(' AND ') 
     "(#{clause})" 
     end.join(' OR ') 

     where clauses 
    end 
    end 
end 
+0

天才!謝謝 – 2016-05-12 17:55:52

3

對於Rails的3:

Person.where(
    Person.where(name: "John").where(lastname: "Smith").where_values.join(' OR ') 
)