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.
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)