← Back to Upcase

Model with has_many association

(Curt) #1

I’m new to rails, and to modeling associations in rails. I have a “Student” model and am planning to add a “Tags” model with associations between the two. Tags need to be dynamically entered by an admin (I’m using the ActiveAdmin gem) and assigned to a student if desired, or to a group of students (a “collection” in ActiveAdmin).

I am not exactly sure how to model this. My thought is to create a Tag model with one column, where each row is a tag name entered by the admin. So perhaps:

class Student < ActiveRecord::Base
	has_many :tags	#student may also have zero tags
	# rest of model

class Tag < ActiveRecord::Base
	attr_accessible :name
	has_and_belongs_to_many :students

And then:

$ rails generate migration create_students_tags_join_table

I’m reading through the rails docs now but suspect the forum may have some insights / corrections / best practices for me in this situation.

(George Brocklehurst) #2

If you’re modelling a many-to-many relationship using has_and_belongs_to_many then you should use has_and_belongs_to_many in both models (you’re currently using has_many at one end and has_and_belongs_to_many at the other end). The has_and_belongs_to_many section of the Rails Guides should point you in the right direction.

Hope that helps!