更新:如果我正確理解你,這裏是一個簡單的設計圖,你想:
,這將是你的類的基本骨架:
class User < ActiveRecord::Base
has_many :ratings
# has_many :categories, :through => :ratings
end
class Category < ActiveRecord::Base
has_many :ratings
# has_many :users, :through => :ratings
end
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :category
validates_uniqueness_of :user_id, :scope => [:category_id]
end
將允許這些查詢:
@category_ratings_by_user = Rating.where("ratings.user_id = ? AND ratings.category_id = ?", user_id, category_id)
@specific_rating = user.ratings.where("ratings.category_id = ?", category_id)
# make nice model methods, you know the deal
# ... if you added the has_many :through,
@john = User.find_by_name("john")
# Two ways to collect all categories that john's ratings belong to:
@johns_categories_1 = @john.ratings.collect { |rating| rating.category }
@johns_categories_2 = @john.categories
@categories_john_likes = @john.categories.where("categories.rating >= ?", 7)
我只是不能確定,爲什麼你想這個
has_many, :through
(這看起來好像不是很多 - 一個評級只屬於
一個用戶,對嗎?)。
這個問題的標題並沒有告訴任何問題/問題 - 你可能想要使它更具描述性。 – 2010-07-16 06:22:36
謝謝約翰,我剛剛更新了我的標題。 – Gotjosh 2010-07-16 13:17:27