This project is archived and is in readonly mode.

#5939 ✓resolved
Chris Anderson

attr_accessor not accessible through accepts_nested_attributes_for

Reported by Chris Anderson | November 9th, 2010 @ 07:17 PM | in 3.x

I'm on rails v2.3.9 and I'm seeing strange behaviour (to me anyways) in accepts_nested_attributes_for. In a certain circumstance the attr_accessor is not available on the nested model.

Tracker 
  has_many :samples
  accepts_nested_attributes_for :samples, :allow_destroy => true

Sample
  attr_accessor :current_user
  belongs_to :tracker

  after_destroy do |sample|
    puts sample.current_user
  end

On the console...

>>t = Tracker.first

>>tracker_attributes = {:note=>"a note",:samples_attributes=>{"1"=>{:sample_note=>"new sample", :current_user=>"console user", :_destroy=>false}}}

>>t.update_attributes(tracker_attributes)
=> '' # no output because _destroy is set to false

>>tracker_attributes = {:note=>"a note",:samples_attributes=>{"1"=>{:id=>1, :sample_note=>"new sample", :current_user=>"console user", :_destroy=>true}}

>>t.update_attributes(tracker_attributes)
=> 'console user'

In the above example everything works as expected and the sample is deleted. If I reload the Tracker after the Sample is created then current_user is not available.

>>t = Tracker.first

>>tracker_attributes = {:note=>"a note",:samples_attributes=>{"1"=>{:sample_note=>"new sample", :current_user=>"console user", :_destroy=>false}}}

>>t.update_attributes(tracker_attributes)
=> 'console user'

>>t = Tracker.first

>>tracker_attributes = {:note=>"a note",:samples_attributes=>{"1"=>{:id=>1, :sample_note=>"new sample", :current_user=>"console user", :_destroy=>true}}

>>t.update_attributes(tracker_attributes)
=> '' # console_user is expected but nil was printed

I'm reloading the Tracker to simulate what I see in a controller. In a controller action I would find the Tracker and then update the attributes. I hope I'm making sense.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Tags