Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
many to many question
7 Posts
many to many question

I have a form that has users. The users can be created or be picked from a drop down. If I submit the form and use Ryan Bates many to many method of creating the relationship I get 2 users, the one already in the db plus the one in the form. The one I create or that was already in the user table prior to submission have to no link but the user in the form gets created again and a link to the form is created. Is there a way to create the relationship of user to form if the user already exists prior to form submission without manually setting the values in the join table?

can you post the code behind the form please? your question is not very clear

OK basically what I am getting at is if you a form model and a user model many to many relationship. If you save the relationship you do something like "form.user.build(:name=>??)". This will create a user with a name of ?? and make the relationship in the join table. If you already have a user with that name how would you create the many to many relationship without creating a user if he already exists?

You could use User.find_or_create(params[:user]) and then attach your associations to the user.

ya how do i do create association if both sides of the associations are known?

There are two lots of helpers that will assist you:

form.users.find_or_create_by_name( params[:user] )

This is not usually what you want, because it will only find the user within the collection of form.users - so you will still end up with multiple users with the same name, as long as no two are attached to the same form. Usually you want this instead:

form.users << User.find_or_create_by_name( params[:user] )

Which will attach either an existing user with the name in params[:user][:name] or create a new user with all the parameters in params[:user] and then attach that.

OK, cool. Awesome. I am starting to get into many to many. I did not realize when the wiki said << it adds to the collection it meant it adds the relationship, doh. Thanks.

7 Posts
Login to add your message