Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Changing foreign key doesn't set relationship as dirty

#1469

When changing a foreign key on a belongs_to relationship, the relationship is not set to dirty.

If I have a model with a relationship to a country, and I change the country_id using attributes=({:country_id => X}) or model.country_id=X, and then access the model.country relationship, it uses the cached country object, instead of looking up the new country_id.

Reported by Paul Mason · November 25th, 2008 @ 04:29 PM

State: duplicate
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Darren
    Darren

    I have come across a problem which I believe is closely related to this.

    If I have a model that belongs_to another, and requires the presence of the relationship (i.e., a valid non-null foreign key), I can get AR to save invalid records in the database.

    For example, with this...

    
    Class Parent < AR::B
    end
    
    class Child < AR::B
      belongs_to :parent # using parent_id
      validates_presence_of :parent
    end
    
    
    ./script/console...
    # child = Child.new
    # child.valid? # false
    # child.parent_id = Parent.first.id # a valid parent
    # child.valid? # true
    # child.parent_id = 9999 # doesn't exist
    # child.valid? # true
    # child.save   # true
    # child.reload
    # child.parent_id # 9999
    # child.parent    # nil
    # child.valid? # false
    

    December 8th, 2008 @ 07:27 PM

  2. Frederick Cheung