简体   繁体   中英

Rails association HABTM

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM