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.

accepts_nested_attributes_for is using the :conditions hash from has_one association

#3609

I don't know if is a bug or not (I believe so because it makes no sense on using the conditions hash) but something like this:

class Account < ActiveRecord::Base
  has_many :users, :dependent => :destroy
  has_one :owner, :class_name => "User", :conditions => {:owner => true, :admin => true}

  accepts_nested_attributes_for :owner
end

class User < ActiveRecord::Base
  belongs_to :account

  attr_accessible :email, :name, :password, :password_confirmation
end

will throw a warning like this on ActiveRecord 2.3.5:

User.create :owner_attributes => {:name => "John Doe"}
#=> WARNING: Can't mass-assign these protected attributes: admin, owner

Reported by Nando Vieira · December 23rd, 2009 @ 04:53 PM

State: invalid
Milestone: none
Assigned to: Eloy Duran Eloy Duran
Importance: none

Activity

  1. José Valim
    José Valim

    For me it makes complete sense to use the conditions hash, as you are creating an owner. If you want to create something which does not have :owner and :admin set to true, you should use another association.

    However, those conditions should not be caught by mass assignment, they should pass free. So in one way or the other, it's bug. :) But probably quite easy to fix!

    December 23rd, 2009 @ 07:54 PM

  2. Eloy Duran
    Eloy Duran

    Could you create a test case for the ActiveRecord test suite which clearly isolates the problem?

    December 24th, 2009 @ 10:46 AM

  3. Eloy Duran
    Eloy Duran
    • Assigned user set to Eloy Duran

    December 30th, 2009 @ 07:47 PM

  4. Eloy Duran
    Eloy Duran
    • State changed from new to invalid

    I can't seem to reproduce this on the current 2-3-stable branch:

    class Project
      has_one :owner, :class_name => 'Author', :conditions => { :owner => true, :admin => true }
      accepts_nested_attributes_for :owner
    end
    
    # without Author attr_accessible
    project = Project.create! :owner_attributes => { :name => 'Bello' }
    p project.owner # => #<Author id: 980190963, name: "Bello", project_id: 980190963, owner: true, admin: true>
    
    # with Author attr_accessible :name
    project = Project.create! :owner_attributes => { :name => 'Bello' }
    p project.owner # => #<Author id: 980190963, name: "Bello", project_id: 980190963, owner: nil, admin: nil>
    

    The fact that it assigns the values from the :conditions hash is indeed intended behavior.

    January 4th, 2010 @ 12:30 PM