2012-04-10 2 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'가 누락 되었습니까? –

+0

@DaveNewton 예, 감사합니다. – LearningRoR

+0

쿼리에 관련 모델 구독이 표시되지 않습니다. 올바른 모델 이름이 맞는지 확인하십시오. – naren

답변

2

includes 방법은 사용자가 생각하는대로 정확하게 수행되지 않습니다. includes에 대한 joins을 대체하고 그것은 당신이 무슨 뜻인지해야한다 : 아마

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에 요청합니다. 두 항목을 함께 사용하면 액티브 레코드는 두 테이블을 조인하고 결과를 사용하여 두 개체 집합을 모두 만드는 (다소 긴) 복합기를 만듭니다.

+0

여전히 나에게 같은 오류가 발생합니다. 이상한. – LearningRoR

+0

나는이 기간 내내'.'이 없어서 일하지 않았다고 생각합니다! 나는 바보 같아. 감사합니다! – LearningRoR