1

現在、ソーシャル メディア アプリを作成しています。ユーザーにカテゴリごとの評価を付けてもらいたいのですが、関連付けはどのように行われますか? セットアップに必要な方法 各ユーザーは、各カテゴリで異なる評価を持っています。

私はそう思います

belongs_to :user
belongs_to :category

UserCategoryRating モデルで。

has_many :user_category_ratings, through => :category

ユーザーモデルでは、これは正しいアプローチですか?

UserCategoryRating テーブルには、User_id 列、Category_id 列、および評価列があり、ユーザーが投票するたびに更新されます (評価は、投票と 1 ~ 5 に基づくスコアの間の AVG です)。

4

2 に答える 2

2

更新:私があなたを正しく理解している場合、これはあなたが望むシンプルなデザインの図です:

UML ダイアグラム

そして、これはクラスの基本的なスケルトンになります:

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)

なぜこれが必要なのかわかりません (これは多対多のようには見えません。評価は1 人のhas_many, :throughユーザーにのみ属しますよね?)。

于 2010-07-16T04:23:20.997 に答える
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
于 2010-07-16T02:54:02.367 に答える