Black Dynamite
Black Dynamite

Reputation: 4147

Ruby refresh object

I am a new to Ruby on Rails and I have a question on refreshing/reloading a relationship. In the following code snippet, I am trying to set the 'store' property on a 'customer' object, then have the customer object returned with the nested store property, not its id. Is there a way I can set the store property, then tell RoR "get me the customer and hydrate the store" without doing another eager read load ?

store_id = params[:id];
store = Store.find( store_id );
session[ :store_id ] = store_id;

customer_id = session[ :customer_id ];
customer = Customer.find( customer_id );
customer.store = store;
customer.save

respond_to do |format|
  format.any(:json) { render :json => customer.to_json  }
end

Any help or any suggestions whether or not they pertain to the original question is GREATLY appreciated.

Upvotes: 1

Views: 499

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84114

On rails 3.1 you can access the association object directly via

customer.association(:store)

In earlier version of rails the association object wasn't exposed directly like this. You can then do stuff like

customer.association(:store).loaded?
customer.association(:store).target = store

This won't check that the customer and the store are associated (i.e. you can stick any old store in there) so be careful.

I'm not sure why you need this though -

customer.store = store

shouldn't cause the store object to be reloaded or anything like that.

Upvotes: 1

alony
alony

Reputation: 10823

to_json with params will do the trick for you:

In your example you need to change only last section (and the store object will not be loaded from db the second time)

respond_to do |format|
  format.any(:json) { render :json => customer.to_json(:methods => :store)  }
end

Upvotes: 3

Related Questions