Forum: Ruby on Rails Adding associations without commiting to database

Posted by Jan Brdo (Guest)
on 2012-11-02 22:59
(Received via mailing list)
I think there is a slight inconsistency in Rails regarding adding
associations between existing records.

Assume Post has_many :tags.

We have an analogy when we want to immediately add the association to
either new or existing child:

> Post.first.tags.create name: "my tag" # commits immediately
> # and to existing tag
> Post.first.tags << Tag.first # commits immediately


But we don't have an analogy to build:

> p = Post.first
> p.tags.build name: "my tag"
> p.save # commits all changes
> # and to existing tag
> # ?


I think this is unfortunate, because I like the idea of building all
changes in memory first and then commiting everything together. I have a
project where this would be useful for me, but is currently not 
possible.
Why not? Discuss.
Posted by David D. (david_d48)
on 2012-11-03 16:12
For that, they use:

p.reload and/or p.tags.reload

The tag is saved when you save p (provided you have :autosave => true 
set)
That's shown here: 
http://api.rubyonrails.org/classes/ActiveRecord/Au... 
under the examples.
Posted by Valery Kvon (Guest)
on 2012-11-05 16:18
(Received via mailing list)
RTFS, and use backdoors :)

Post.first.tags.target << Tag.first
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.