2012-04-10 26 views
3

我不確定這裏發生了什麼。我有一個範圍,我試圖創建一個與我協會的工作原理:rails:使用相關模型的列:其中

class Subscription < ActiveRecord::Base 
    belongs_to :subscriber, :class_name => "User" 
    belongs_to :subscribable, :polymorphic => true 
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 

class Product < ActiveRecord::Base 
    has_many :subscriptions, :as => :subscribable, :dependent => :destroy 

    def self.lower_prices 
     Product.includes(:subscriptions). 
     where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit") 
    end 
end 

我想比較產品認購的價格較低,但這給我的錯誤:

ActiveRecord::StatementInvalid in Pages#subscribed_products 

PGError: ERROR: missing FROM-clause entry for table "subscriptions" 
LINE 1: ... WHERE (user_id != 2) AND (products.price < subscripti... 
                  ^
: SELECT COUNT(*) FROM "products" WHERE (user_id != 2) AND (products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit) 

這裏有什麼問題?

+0

缺少'def'是一個錯字嗎? – 2012-04-10 22:48:06

+0

@DaveNewton是的,忘了它,謝謝。 – LearningRoR 2012-04-10 22:50:56

+0

我在查詢中沒有看到關聯的模型訂閱是否確定您有正確的模型名稱 – naren 2012-04-10 23:05:30

回答

2

includes方法並不完全符合您的想法。替換joinsincludes,它應該你是什麼意思:

Product.joins(:subscriptions). 
     where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit") 

或者是:

Product.includes(:subscriptions).joins(:subscriptions). 
     where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit") 

joins轉化爲結果的SQL查詢JOIN,這樣你就可以執行WHERE在連接表子句。 include只是要求Active Record執行另一個查詢來選擇給定表中的所有相關記錄。如果您將兩者結合在一起,則Active Record會創建一個(相當長)的all-in-one,它們都會連接這兩個表並使用結果創建兩組對象。

+0

它仍然給我同樣的錯誤。奇怪。 – LearningRoR 2012-04-11 01:52:00

+0

我覺得這整個過程都不​​起作用,因爲一段時間'.'失蹤了!我覺得很愚蠢。謝謝你,先生! – LearningRoR 2012-04-11 02:12:34