开发者

Nested resource check

I have a Rails form, where is reported the user and the skills of the user (the association is many to many) so I use accepted_nested resource in the form

Everything works okkey, the user have the chance to create a new skill and associate themself to it.

The problem is that if a skill with the same name already exists, I don't want that one more s开发者_如何学Pythonkill with the same name is created, I just want an association with the user and the already existing skill.

Do I have to leave the nested resource approach and performing some controls in the controller in order to choose if create or just associate the skill ?

Tnx


You could use Rails' find_or_create_by method to find or create the skill by whatever criteria you choose. Then add that to the user's skill collection. I don't know what your code looks like, but something like this:

@skill = Skill.find_or_create_by_name(params[:skill][:name])
@user.skills << @skill
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜