Search code examples
ruby-on-railsruby-on-rails-3activerecordhas-and-belongs-to-manyrating-system

How to create a rating system for has_many - has_and_belongs_to_many relation in Rails


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.


Solution

  • 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.