rails / protected_attributes

Protect attributes from mass-assignment in ActiveRecord models.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

protected_attributes + nested attributes invokes callbacks twice

pkmiec opened this issue · comments

I upgraded from Rails 4.0 to Rails 4.1 and noticed that some callbacks are being invoked twice. I've narrowed it down to the interaction between protected_attributes gem and nested attributes.

I've distilled the problem in a simple app (affects both Rails 4.1 and Rails 4.2),

but it works with Rails 4.0: https://github.com/pkmiec/buggy/tree/rails40

The app basically has,

class Portfolio < ActiveRecord::Base
  belongs_to :contact_info
  accepts_nested_attributes_for :contact_info

  after_update do |obj|
    puts "AFTER_UPDATE"
  end
end

class ContactInfo < ActiveRecord::Base
  has_one :portfolio
end

class PortfolioTest < ActiveSupport::TestCase
  test "the truth" do
    ci = ContactInfo.create!
    portfolio = Portfolio.create!(:contact_info_id => ci.id)

    attrs = {
      :contact_info_attributes => {
      }
    }

    puts "--- begin"
    portfolio.attributes = attrs
    puts "--- middle"
    portfolio.save!
    puts "--- end"
  end
end

Running the test,

%> rake
--- begin
--- middle
AFTER_UPDATE
AFTER_UPDATE
--- end

If you comment out gem 'protected_attributed' from the Gemfile you get the correct behavior,

%> rake
--- begin
--- middle
AFTER_UPDATE
--- end