Search code examples
ruby-on-railsmany-to-manymodelspolymorphic-associations

Models with many-to-many relationships


I have a test app that I'm trying to setup for practice, the app has Users, who can choose up to 6 Interest Categories when they register.

So, the user can have many interest categories, which will have many "sub" interests ... I am a little confused as to how I can set this up, so that when the user registers, they can choose the 6 interest categories by way of checkboxes on the user registration form.

Should I be using polymorphic associations, or should I create an interest and interest_category model with the user model and the interest_category model using something like:

has_many :interest_categories, :through => :interests ?

Also, how can I get the form to save these interest_categories? I've tried f.fields_for :interest_categories, but they aren't saving.

Any ideas?


Solution

  • I would use has_many :categories, :through => :categorizables. You could then add a string field called :category_type to the Categorizable model and input "interest" for this case and another string for other cases.

    In this way you would have a has many through relationship that's agnostic to the relationship type.

    You can then query by User.categorizables.where(:category_type => "interest") or setup a scope.

    You also might want to consider watching this Railscast: http://railscasts.com/episodes/17-habtm-checkboxes

    It's a little outdated, but most likely helpful in setting up your form. There's many ways to approach this, but that's how I'd do it.