Multiple foreign keys referenced by a single Rails model

I have a typical user model (username, password, name, etc.). I want to allow users to attach the three selected categories to their account. Each of the three categories exists in the category model.

How to associate three foreign keys from a category with one user without using a staging table for tracking? Each category can belong to any number of users, but each user can have only three categories.

I played with has_many: through, but I really don't think a relationship table is needed, and that would generate a lot of coding at my end to work with it.

Any ideas?

+1
ruby-on-rails
source share
2 answers

In terms of code support, although you can limit the number of categories that a user can select to 3 right now, you may not want to encode it with this restriction. You will kick yourself later when you want to increase it to 5 or decrease it to 1. My suggestion was to simply use has_and_belongs_to_many with a connection table (you don't need :through , because what I can tell you don't need from connection model, just a connection table). Using HABTM will automatically use the connection table, so you don’t have to worry about writing code to process it. Just make sure you name the connection table and its columns correctly.

Regarding the actual restriction of the user to only three categories, it is easy to implement this restriction in the view / controller (i.e., restrict the interface so that they cannot select more than 3).

I am sure you have already read this, but in case you have not done so, here are the docs for the HABTM.

+2
source share

HABTM is your best bet. To limit users to three categories, add model level confirmation:

 class User < ActiveRecord::Base has_and_belongs_to_many :categories validate :no_more_than_three_categories protected def no_more_than_three_categories self.errors.add(:categories, "may not have more than three") if categories.size > 3 end end 

Pull the magic number 3 as you wish into the level constant or configuration setting.

And don't be afraid of the code. Do it right, and the code will be afraid of you.

+2
source share

All Articles