Jonathan Viney
2006-Jul-31 09:25 UTC
Updating a belongs_to foreign key leaves the old association object available
Perhaps this is intentional, but it seems unlikely: class Person < ActiveRecord::Base belongs_to :school end p = Person.find(:first) p.school # nil p.school_id = School.find_by_name(''High School'').id p.school.name # High School p.school_id = School.find_by_name(''Primary School'').id p.school.name # High School <= Shouldn''t this be Primary School? p.school.id == p.school_id # false !!! Of course, p.school(:reload) works fine, but I think it would be nice for the association accessor to check that the foreign keys match up and reload the association if they don''t. This should only be necessary for belongs_to. A more disturbing example may be something like: def save @person = Person.find(params[:id], :include => :school) @person.update_attributes(params[:person]) # @person.school will refer to the old school, even if a new school_id was passed in the params end Thoughts? -Jonathan.
Michael Koziarski
2006-Jul-31 09:31 UTC
Re: Updating a belongs_to foreign key leaves the old association object available
> p = Person.find(:first) > p.school # nil > p.school_id = School.find_by_name(''High School'').id > p.school.name # High SchoolYou should be assigning .school= here. Why are you working with the id?> p.school_id = School.find_by_name(''Primary School'').id > p.school.name # High School <= Shouldn''t this be Primary School? > p.school.id == p.school_id # false !!!Again, the .school_id accessors aren''t really meant for use like this. I suppose the accessors could check the ids, but it seems like a lot of work for a corner case. An alternative would be to let the school_id accessor use school.id if the proxy''s been loaded. -- Cheers Koz
Jonathan Viney
2006-Jul-31 10:00 UTC
Re: Updating a belongs_to foreign key leaves the old association object available
Isn''t the standard way of updating relationships like this to have a select box with name="person[school_id]" which will be updated with update_attributes, like in the second example? I''ve attached a patch which fixes the behaviour. I guess school_id could access school.id, and school_id= would have to set @school nil. It makes more sense to me to put it in the association accessor, rather than modifiying the attribute accessors. -Jonathan. On 7/31/06, Michael Koziarski <michael@koziarski.com> wrote:> Again, the .school_id accessors aren''t really meant for use like this. > I suppose the accessors could check the ids, but it seems like a lot > of work for a corner case. An alternative would be to let the > school_id accessor use school.id if the proxy''s been loaded. > -- > Cheers > > Koz_______________________________________________ Rails-core mailing list Rails-core@lists.rubyonrails.org http://lists.rubyonrails.org/mailman/listinfo/rails-core