Reputation: 1535
I need some help in creating association for my new rails application.
I have two models User
and Profession
. A user might have many professions and profession might belongs to many users.
I can do HABTM
association in both the models.
User has_and_belongs_to_many :professions
Profession has_and_belongs_to_many :users
I want professions table should hold only unique profession name and assign them to many users. But if I try to create professions for users like bellow
user1.professions.create(name: "Dev")
user2.professions.create(name: "Dev")
Both profession "Dev" will get saved in professions table.
How to save unique profession name in Profession model and can assign them to many users?
Upvotes: 2
Views: 101
Reputation: 2745
I would suggest splitting it into two steps.
At first find or create profession:
profession = Profession.find_or_create_by(name: "Dev")
Then assign the profession to user:
user1.professions << profession
user2.professions << profession
I would also recommend to set a unique index on professions
table's name
column. It will guarantee the uniqueness.
Upvotes: 2
Reputation: 94
Try to create association as below:
profession = Profession.find_or_create_by(name: "Dev")
user1.professions << profession
profession = Profession.find_or_create_by(name: "Dev")
user2.professions << profession
Upvotes: 1