I have three models as you can see below.
class Watchedfamily < ActiveRecord::Base
has_many :watchedmembers, :dependent => :destroy
accepts_nested_attributes_for :watchedmembers
has_many :old_watchedmembers, :dependent => :destroy
accepts_nested_attributes_for :old_watchedmembers
end
class OldWatchedmember < ActiveRecord::Base
belongs_to :watchedfamily
end
class Watchedmember < ActiveRecord::Base
belongs_to :watchedfamily
end
Now I have a method in my controller that is (for a given
watchedfamily) copying all entries of watchedmembers to
old_watchedmembers and then deleting the watchedmember entries.
Finally I am updating the watchedfamily with new watchedmembers. I
just need it for comparing old members with actual members.
Everything is working great in my database. I only have one problem in
the controller below. I need the @family.watchedmembers for a next
step, but the problem is that the @family.watchedmembers variable has
the old and the new members in its memory. The database is updated and
correct! It is only the @family.watchedmembers variable that has both
members in it.
My solution is to just call again: ‘@watchedfamily =
Watchedfamily.find(id)’ to get the recent data from the db.
Is that the only possibily or is that bad because of additional load
on the db?
id = params[:id]
@watchedfamily = Watchedfamily.find(id)
@watchedfamily.watchedmembers.each do |member|
params = {:watchedfamily => {:old_watchedmembers_attributes =>
MyExistingMemberEntries } }
@watchedfamily.update_attributes(params[:watchedfamily]) #copy
watchedmember to old_watchedmember
member.destroy #destroy watchedmember
end
params = {:watchedfamily => {:watchedmembers_attributes =>
MyNewMemberEntries } }
@watchedfamily.update_attributes(params[:watchedfamily]) #create
recent watchedmembers
@watchedfamily = Watchedfamily.find(id) #call the variable again from
the db to get the actual data!
@watchedfamily.watchedmembers.each do |x|
…#some code for the next step
end
I hope someone can give me a hint!
Cheers,
Sebastian