Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mass_assignment_authorizer and nested attributes

I'm using dynamic attr_accessible as per this article:

http://asciicasts.com/episodes/237-dynamic-attr-accessible

It works fine. But I haven't found an elegant way to make it work with nested attributes. Here's some simplified code:

class Company < ActiveRecord::Base
  has_many :employees

  accepts_nested_attributes_for :employees
end

class Employee < ActiveRecord::Base
  belongs_to :company

  attr_protected :salary

  attr_accessor :accessible

  def mass_assignment_authorizer  
    if accessible == :all
      ActiveModel::MassAssignmentSecurity::BlackList.new
    else
      super + (accessible || [])
    end
  end 
end

Let's say I have an admin interface with a RESTful form for a Company. On this form, I have fields for employees_attributes, including blank fields to create new Employees. I can't find a way to call Employee#accessible= in this context. Browsing through the ActiveRecord source code, it seems that this might be impossible: in the remotest part of a very deep call stack, nested associations just result in Employee.new being called with the attributes.

I'd thought about creating a special attribute that could be passed in through mass assignment. If the attribute's value were the right code, the Employee instance would set @accessible to :all. But I don't think there's a way to guarantee that this attribute gets set before the protected attributes.

Is there any way to make dynamic protected attributes work with nested attributes?

like image 917
rlkw1024 Avatar asked Feb 07 '11 20:02

rlkw1024


People also ask

What are nested attributes?

Nested attributes are a way of applying sub-categories to your attributes. For instance, instead of having a single searchable attribute price , you may set up some sub-categories: price.net , price.

What is nested attributes rails?

Rails provide a powerful mechanism for creating rich forms called 'nested attributes' easily. This enables more than one model to be combined in forms while maintaining the same basic code pattern with simple single model form. Nested attributes allow attributes to be saved through the parent on associated records.


1 Answers

I'm new to rails, and have had boatloads of trouble trying to get nested attributes to work myself, but I found that I had to add the nested attributes to my accessible list.

class Company < ActiveRecord::Base
  has_many :employees

  accepts_nested_attributes_for :employees

  attr_accessible :employees_attributes
end

My understanding is that accepts_nested_attributes_for creates that special employees_attributes, but when you default all attributes to non-accessible (which I believe the asciicast does) you won't be able to use it.

I hope that helps.

like image 98
Geoff Avatar answered Nov 03 '22 19:11

Geoff