0

I have an app where:

User has_many Openings

Opening belongs to User & has_and_belongs_to_many Categories

Category has_and_belongs_to_many Openings

I'm trying to create a rating system where the user rates each opening per category, and am struggling to see what relations I need where. Could anyone help point me in the right direction please?

Basically I want the rating to belong to a opening_category relation.

Chris Edwards
  • 3,514
  • 2
  • 33
  • 40

1 Answers1

1

Instead of using has_and_belongs_to_many association, you want the has_many through relation

Thus, you create a new model

class OpeningCategory
  belongs_to :opening
  belongs_to :category
end

Then you can use Opening has_many :categories, :through => :opening_categories, and Category has_many :openings, :through => :opening_categories.

Your rating can be done with the OpeningCategory, whether that is an average rating column, or a separate Rating model which :belongs_to :opening_categories.

ronalchn
  • 12,225
  • 10
  • 51
  • 61
  • Ok thanks that makes a lot more sense. I guess I would be able to tie this into the user model then also? – Chris Edwards Aug 17 '12 at 10:06
  • Cool. How then do I call each rating? I.e. @opening.categories.each do |category| then category.rating? – Chris Edwards Aug 17 '12 at 10:45
  • And also, submit a rating / create form fields for the opening_category rating? Also I believe the OpeningCategory should have_one :rating as each should only have one (5-star based) rating – Chris Edwards Aug 17 '12 at 10:51
  • @opening.opening_categories.each do |oc| oc.rating end – ronalchn Aug 17 '12 at 11:01
  • Sorry, I'm having a lot of trouble trying to do the form fields to update the rating model. I'm trying to loop through the opening_categories per opening, and allow editing the opening_categories.rating fields - so you would see the category title and the star rating fields underneath – Chris Edwards Aug 17 '12 at 21:37
  • With editing nested attributes, you need to do some extra stuff. Try using fields_for as explained in: http://rubysource.com/complex-rails-forms-with-nested-attributes/ – ronalchn Aug 17 '12 at 23:14
  • Yeh I'm having some strange problem, maybe I'm missing something. I've added the loop to this gist https://gist.github.com/3389799 – Chris Edwards Aug 18 '12 at 20:50