SuperString
SuperString

Reputation: 22519

rails model relationship

Hi I am really new to rails and I am trying to create a products ratings model.

So there's users (name, email, pw)

Users has a list of products that the user has rated. With a rating (1-10) and a comment.

Each product has its description, a list of the users who rated them, the rating and the comment.

How should I create the relationship? Should I have 3 models, user, rating, product, or can I get by with just user and product?

Also what would be the :has_many .etc relationship look like?

Upvotes: 0

Views: 108

Answers (2)

Michael Durrant
Michael Durrant

Reputation: 96454

This would a great case for a has_many :through =>

User Model.

User has_many :ratings
User has_many :products, :though => :ratings

Rating Model.

belongs_to :user
belongs_to :product

Product Model.

Product has_many :ratings
Product has_many :users, :through => ratings

n.b. this is now considered superior to has_and_belongs_to_many which many folks consider to be basically deprecated at this point.
Personally I've never liked using has_many_and_belongs_to, both as it works and also because of the frequent re-work to turn it into has_many, :through as soon as an additional attribute is desired on the join model (ratings in this case).
Actually you want a rating 'level' so you already have a case for the has_many, :through !

Upvotes: 1

Matt Grande
Matt Grande

Reputation: 12157

Here's what I would do

class User
  has_many :ratings
  has_many :products, :through => :ratings
end

class Product
  has_many :ratings
  has_many :users, :through => :ratings
end

class Rating
  belongs_to :user
  belongs_to :product
end

This way if you wanted to get all the users that have rated a product, you can say product.users.

Upvotes: 3

Related Questions