Nested Has_one Relationship with Fields_for and Attr_accessible in Model Class

5 Comments
Tags: , ,
Posted 26 Jul 2009 in Ruby on Rails

To make child attributes accessible to your model through a nested forms (Rails 2.3) you’ll need to add the “#{child_class}_attributes” to the attr_accessible method in your parent class. If you don’t use attr_accessible in your parent model (you would do this to restrict certain attributes to be accessed via a web form) then you should be all set.

Below is an example where User has_one Profile with the favorite_color attribute being set/updated in the nested form.

class User < ActiveRecord::Base
  has_one :profile #child class
  accepts_nested_attributes_for :profile
  attr_accessible :profile_attributes # the format is the child_class followed by the "_attributes"
end

And the form would like this...

<% form_for @current_user do |f| %>
   <% f.fields_for :profile do |profile| %>
     <%= profile.text_field :favorite_color %>
  <% end %>
<% end %>

Related posts:

  1. Nested Attributes in a Form for Has_One Model Association in Rails
  2. Dynamic Attributes in Python Model Class
  3. Override to_param method in model to get pseudo permalinks without any work
  4. Accessing Links in Nested TD Cells with Prototype
  5. Trouble Using Attr_Accessor in Rails Models and Forms

5 Comments

  1. Brad

    Thank you! Saved me from having to read the API docs! +1 internets for you, sir!

  2. I cant see your code in Safari, in FF is ok

  3. admin

    Thanks for the heads up. Not sure what the problem is but I’ll take a look at it. It might be the “” characters aren’t being escaped properly!

  4. Kirk

    Hi, I thank you for your infromation here.

    For some reason after following the information here in a similar User-Profile thing, it still says WARNING: Can’t mass-assign these protected attributes: profile

    I’m using Restful authentication User model for this, im wondering if there is other stuff going on?

    Any ideas?

    Thanks

  5. admin

    With restful authentication there is a chunk of code in the user model

      # HACK HACK HACK -- how to do attr_accessible from here?
      # prevents a user from submitting a crafted form that bypasses activation
      # anything else you want your user to change should be added here.
      attr_accessible :login, :email, :name, :password, :password_confirmation
    

    Try adding :profile to the attr_accessible list or… commenting out the attr_accessible line altogether. You can use attr_protected instead and explicitly list attributes unavailable for mas assignment. A blacklist as opposed to a whitelist approach to protecting your model attributes.



Add Your Comment