Hi all!
I find association collections to be quite hard to understand and use.
I have a Leg class that has_many :choices, and a Choice class that
belongs_to :leg. In a controller I want to update both a Leg and its
Choices. If I do it like this:
@leg.choices.update params[:choice].keys, params[:choice].values
It updates the database directly (or more specifically only updates
records that validates). So if I want to make the update to the @leg and
@leg.choices as an atomic action I guess that I will have to introduce a
transaction. However, then all the changes will be lost for the user
since the form will reflect the unchanged database, right?
So then I tried to first make the updates to the choices and then save
everything in a transaction, like this:
@leg.attributes = params[:leg]
choices = params[:choice]
if choices
choices.each do |key, value|
@leg.choices.find(key).attributes = value
end
end
if request.post?
Leg.transaction do
@leg.save!
@leg.choices.each {|choice| choice.save! }
end
But it tuns out that I can’t make changes to individual records in the
association collection, so the @leg.choices.find().attributes=() doesn’t
change anything.
So now I’m basically out of ideas. Does anyone got any pointers?
Thanks in advance!
/Jonas