views:

473

answers:

3

I have a couple models which are associated with the has_many belongs_to pair. For the sake of demonstration, a client has one server but a server has many clients. I might do something like this:

client1.server = the_server
client2.server = the_server
client3.server = the_server

My actual application is quite a bit more complex than this, but the example will work for illustration.

I want to inspect the associations between these objects before I save them. ActiveRecord doesn't update their information until they are saved though. In the example above, the_server has no idea who client1, client2, or client3 are until one of them gets saved. I'm sure that this helps active_record's efficiency, but it leaves model instances in memory in an inconsistent state.

Is there anything I can call on the clients or on the server that will cause them to update their states?

A: 

Call #reload on the objects to update them.

Ryan Bigg
This requires the objects be saved first doesn't it? reload says get the info from the db again. If client1,2 and 3 are not saved their is nothing to reload.
srboisvert
That is my understanding, as well. I don't want to refresh from the DB - quite the opposite: I want the objects to refresh as though they had been saved.
A: 

If you start off like this:

client1 = the_server.clients.build(:name => 'a client', ...)

Then you should get what you're looking for I think.

EDIT:

Oops, I re-read your post and realized that the_server hasn't been saved yet either. In that case perhaps:

client1.server = the_server
the_server.clients << client1

(be aware that this will save client1 if the_server is already saved)

or:

the_server.clients.build(:name => 'some client', ..., :server => the_server)

A bit redundant so perhaps there's a better way out there.

Jordan Brough
A: 

If you use the reverse way of creating the association, then you are able to look at the models prior to them being saved:

the_server.clients << client1
the_server.clients << client2
the_server.clients << client3

Note, however, that you can only call client1.server immediately after if the_server already exists.

Drew Blas