2012-04-10 2 views
0

У меня есть две модели:Как создать область, которая сравнивает объединение?

class Subscription 
    belongs_to :subscriber, :class_name => "User" 
    belongs_to :subscribable, :polymorphic => true 
end 

class Product 
    belongs_to :user 
    has_many :subscriptions, :as => :subscribable, :dependent => :destroy 
end 

create_table :products do |t| 
    t.string :name 
    t.decimal :price 
    t.decimal :cost_per_unit 
    t.integer :user_id 
end 

create_table :subscriptions do |t| 
    t.string :name 
    t.decimal :price 
    t.decimal :cost_per_unit 
    t.integer :subscriber_id 
    t.integer :subscribable_id 
    t.string :subscribable_type 
end 

В моей модели продукта, я пытаюсь сделать сферу, сравнивающий price или cost_per_unit в Product к Subscription. Я просто не знаю, как я буду писать это в SQL. Так должно быть что-то вроде:

class Product 
    def self.lower_prices 
    where(self.price < self.subscription.price OR self.cost_per_unit < self.subscription.cost_per_unit) 
    end 
end 

Как бы это написать?

ответ

1

Вам нужно будет указать фрагмент sql в предложении where, а также использовать соединение для получения данных из таблицы подписки.

У меня нет доступа к моей машине разработки, чтобы проверить это, но это должно указывать на вас в правильном направлении, надеюсь.

class Product 
    has_many :subscriptions, :as => :subscribable, :dependent => :destroy 
    self.lower_prices 
    Product.includes(:subscription). 
    where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit") 
    end 
end 
Смежные вопросы