[英]Adding a Rating to each User per category on Ruby on Rails
Right now I'm building a social media app, where i want an user to have a rating per category, how would the association go? 现在,我正在构建一个社交媒体应用程序,我希望用户对每个类别进行评分,关联度如何? The way it needs to be setup it's Each user will have a different rating in each category.
每个用户在每个类别中的评分都会有所不同。
I'm think that 我认为
belongs_to :user
belongs_to :category
in the UserCategoryRating model. 在UserCategoryRating模型中。
and 和
has_many :user_category_ratings, through => :category
on the User model, Is this the correct approach? 在用户模型上,这是正确的方法吗?
The UserCategoryRating table has the User_id column, Category_id column, and the rating column, that updates each time an user gets votes (The rating it's just the AVG between votes and the score based on 1-5) UserCategoryRating表具有“ User_id”列,“ Category_id”列和“评级”列,该列在用户每次获得投票时都会更新(评级只是在投票和基于1-5的得分之间的AVG)
UPDATE : If I'm understanding you correctly, here is a diagram of the simple design you'd like: 更新 :如果我对您的理解正确,这是您想要的简单设计图:
And this would be the basic skeleton of your classes: 这将是您的课程的基本框架:
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
Will allow for these query: 将允许这些查询:
@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)
I'm just unsure as to why you want this
has_many, :through
(this doesn't seem like a many to many -- a rating only belongs to
one user, correct?).
我不确定您为什么要使用
has_many, :through
(这似乎不是很多对很多-评级仅属于
一个用户,对吗?)。
I will use the following data model: 我将使用以下数据模型:
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
Now when you want to update the score of a user for a category 现在,当您要更新某个类别的用户分数时
uc = u.user_categories.find_by_category_id(id)
uc.score = score
uc.save
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.