How can I get a list of the associated models that were updated during the save of an instance of ActiveRecord?

StackOverflow https://stackoverflow.com/questions/22934105

Pregunta

I'm passing params to a model instance and saving it with update_attributes. It is associated with several other models and I've configured it to update some of these with accepts_nested_attributes_for.

This is very nice and clean as I only have to update the one model, but I'd like to get a list of the associated(nested) models that were also updated so that I can give the user feedback about some of the fields that have changed.

Is there a way to do this, or am I approaching the problem in the wrong way?

¿Fue útil?

Solución

I've found a solution to my question, maybe not the best one but it will work.

For a list of models that are associated and have accepts_nested_attributes_for configured we go:

associations = ModelClass.reflect_on_all_autosave_associations()

Each of these association objects has a name attribute(the association name), which can be used to access the association on the instance, and then we can check whether this association has changed:

associations.each{|assoc|
    model_instance.send(assoc.name).changed?
}

It should be noted that we cannot use update_attributes with this solution, as all the models are saved before we can check whether anything has changed. So we have to assign_attributes and save the model in separate steps:

model_instance.assign_attributes(params[:model_instance])
// check for changes on associations here
model_instance.save()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top