1

現在我正在構建一個社交媒體應用,我希望用戶對每個類別有一個評級,該關聯將如何進行?它需要進行設置的方式每個用戶在每個類別中都會有不同的評分。在Ruby on Rails上爲每個用戶添加評分

我認爲

belongs_to :user 
belongs_to :category 
在UserCategoryRating模型

has_many :user_category_ratings, through => :category 
上的用戶模型

,這是正確的做法?

的UserCategoryRating表中有user_id列,CATEGORY_ID列,評級列,每一個用戶得到票時間更新(這只是AVG票和分數之間的等級基於1-5)

+1

這個問題的標題並沒有告訴任何問題/問題 - 你可能想要使它更具描述性。 – 2010-07-16 06:22:36

+0

謝謝約翰,我剛剛更新了我的標題。 – Gotjosh 2010-07-16 13:17:27

回答

2

更新:如果我正確理解你,這裏是一個簡單的設計圖,你想:

UML Diagram

,這將是你的類的基本骨架:

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(這看起來好像不是很多 - 一個評級只屬於 一個用戶,對嗎?)。

+0

是的,評級只屬於一個用戶,但用戶可以有多個評級(每個類別一個),所以不會是多對多的關係? – Gotjosh 2010-07-16 13:16:26

+0

即使其他解決方案工作,你似乎更清潔,我有興趣聽到你回來:D – Gotjosh 2010-07-16 13:39:08

+0

@Gotjosh,我不知道我完全理解你的問題,然後...是多個評級,一個用戶除了「分數」值之外,還有一個類別可以區分嗎?我認爲它們是不同類型的,這就是爲什麼我添加':type_of_rating'字段並添加了範圍唯一性驗證程序的原因。否則,如果收視率沒有真正區分,那麼您可以刪除該線並製作一個驗證器,以允許user_ratings不必是唯一的。你明白我想說什麼嗎? – 2010-07-16 14:48:35

1

我會用以下數據模型:

class User 
    has_many :user_categories 
    has_many :categories, :through => :user_categories 
end 

class UserCategory 
    belongs_to :user 
    belongs_to :category 
    # this model stores the average score also. 
end 

class Category 
    has_many :user_categories 
    has_many :users, :through => :user_categories 
end 

現在,當你想更新用戶的評分類別

uc = u.user_categories.find_by_category_id(id) 
uc.score = score 
uc.save 
+0

我不認爲這就是我要找的,用戶不需要有類別,文章需要有類別,我已經得到了工作。我需要的是每個類別中每個用戶的評分/評分。 – Gotjosh 2010-07-16 03:28:19

+0

我已經更新了我的答案。我確信您可以使用建議的模型爲用戶和類別組合存儲分數。 – 2010-07-16 04:03:34

+0

我試着這個解決方案,它似乎並沒有在我的軌道控制檯上工作,我創建了一個UserCategory對象,然後從數據庫中搜索一個類別,然後是一個用戶,然後嘗試將它們附加到UC對象它不工作。 – Gotjosh 2010-07-16 13:33:49