selva4...@gmail.com wrote in post #1117870:
> Hi,
>
> The @user object is getting saved first. That time, there is no
> instuition membership attached to it. So one is getting created. Then
> when you save the instuition membership again inside the controller it
> also gets saved.
>
> Is this clear?

You just restated what i had initially written.


The "problem" is something to do with how rails connects newly 
initialized objects that are in memory but not yet in the database.

We have built two objects like this
u = User.new
im = InstitutionMembership.new :user => u

At that point the u (User) object doesn't know anything about the im 
object. Saving the u object does not trigger an autosave on the 
association, and the create callback creates a new membership. That's 
somewhat expected.

The odd issues appear after -
u = User.new
im = InstitutionMembership.new :user => u
u.save
im.save

'im' is aware of the user object, however it is not able to validate 
against it. When it attempts to validate, the user_id==NULL. At the very 
next log entry though, it saves itself with the correct user_id. So 
somewhere between the validate callbacks, and the create and commit 
callbacks, the 'im' object refreshed the user object and retrieved the 
user_id. Also the new_record? flag on 'im' is still set, so a new row is 
created.

One of the better solutions was actually to do:
u = User.new
im = u.institution_memberships.build

This is able to properly connect the objects in memory, and the process 
works smoothly. The association is autosaved on u.save

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/fc9852aaa5e23f13c8185ac013988a08%40ruby-forum.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to