开发者

Adding a Rating to each User per category on Ruby on Rails

开发者 https://www.devze.com 2023-01-07 18:43 出处:网络
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

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 User开发者_如何转开发CategoryRating model.

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)


UPDATE: If I'm understanding you correctly, here is a diagram of the simple design you'd like:

UML Diagram

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?).


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号