2011-07-09 56 views
0

我有以下型號,與他們相關協會:Rails的 - 需要幫助建立鬆散耦合協會

class User < ActiveRecord::Base 
    has_many :reviews 
    has_many :ratings 
end 

class Product < ActiveRecord::Base 
    has_many :reviews 
    has_many :ratings 
end 

class Review < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :user 
end 

class Rating < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :user 
end 

給出了具體的Rating,我需要得到相應的Review(如果您的評價存在)。

我需要保持ratingsreviews鬆耦合。 (我不想設置我的模式,使一個Reviewbelongs_to一個Rating

我應該怎樣建立一個rating's協會reviews

一旦我在視圖中使用特定的評分,我可以撥打@rating.product.reviews.where(:user_id => @rating.user.id).first,但如果可能,我希望它更清潔/更高效。

任何想法?

謝謝。

回答

2

嘗試使用:條件,像這樣:

class Rating < ActiveRecord::Base 
    has_many :reviews, 
      :through => :user, 
      :source => :reviews, 
      :conditions => ['#{Review.table_name}.product_id = #{product_id}'] 
end 

如果不工作,做到這一點,而不是(非常像什麼@RobinBrouwer回答):

class Rating < ActiveRecord::Base 
    def reviews 
    user.reviews.where(:product => product) 
    end 
end 
+1

他並不需要指定用戶兩次 - 「user.reviews.where(:product => product)」就足夠了。 –

+0

是的,謝謝,留下了一個意外,固定。 – jimworm

+0

你能解釋一下這裏發生了什麼:「{:product_id =>&:product_id}」「?謝謝。 – johnnycakes

0

您可以創建一個has_many :through關係以獲得所有評論。

class Rating < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :user 
    has_many :product_reviews, :through => :product, :source => :reviews 
end 

您現在可以執行以下操作如同上面一樣做同樣的:

@rating.product_reviews.where(:user_id => @rating.user.id).first 

不是真的有很大的改進。你可以把它放在一個實例方法裏面清理東西:

def review 
    product_reviews.where(:user_id => user_id).first 
end 

現在,你可以簡單地執行以下操作來獲得相同的結果:

@rating.review 

就是這樣。