Search code examples
ruby-on-railscachingruby-on-rails-4modelmodel-associations

Can't use updated model with association in the same view


I have a @parent model which has many @kids model

@parent = Parent.find(par_id)
@kid = @parent.kids.first

@parent.update_attributes(params) #change parent's name

doing @kid.parent would be different than @parent eventhough @kid.parent == @parent the only difference is a different Parent.name

this causes the view for the kid to be rendered wrong with the old parent name in view:

<%= @kid.parent.name %> #=> this renders the old name and not the newly updated on

Is there a way to refresh the association or a model?


Solution

  • You could use ActiveRecord's reload method.

    @kid.parent.reload # or just @kid.reload
    @kid.parent.name # the new name, freshly fetched from the DB