1

I know this question has been asked a bunch of times. I already have nested fields_for in my app many times w/o issue so I'm confused as to why its not working this time. I apologize for bringing this topic up again.

I have a user model. A user can have many accounts. To prevent a user from existing w/o at least one account I have a semantic_fields_for nested in the new user form with just one input for setting account role_id.

class User

    attr_accessible :accounts_attributes
    has_many :accounts, :dependent => :destroy
    accepts_nested_attributes_for :accounts

class Account

    attr_accessible :role_id, :user_id, :status
    belongs_to :role
    belongs_to :user

users/new

    <%= f.semantic_fields_for :accounts do |account| %>
    <%= account.input :role, :as => :select, :collection => @roles, :label => "Account" %>
    <% end %>

So, to recap: I have the association set up between users and accounts, users model includes accepts_nested_attributes_for, users model includes attr_accessible :accounts_attributes, semantic_fields_for is set up correctly. The error I get is:

Can't mass-assign protected attributes: accounts

The stack trace from the submitted form includes all the correct variables. Account role_id is being set correctly by the nested attribute. The record is simply being rejected for mass-assignment error but it sure seems my attributes are all properly protected.

Using Rails 3.2.3 and Formtastic 2.2.

EDITED

class UsersController

def new

  @user = User.new         
  @user.accounts.build

end

users/new

    <%= semantic_form_for :user, :url => users_path do |f| -%>
    
    <%= f.inputs do %>
        <%= f.input :name %>
        <%= f.input :username %>
    <%= f.input :email %>   
        <%= f.input :password, :as => :password %>
        <%= f.input :password_confirmation, :label => "Confirm Password", :as => :password %>
    <%= f.input :school_id, :as => :hidden, :input_html => {:value => @school.id} %>        

        <%= f.semantic_fields_for :accounts do |account| %>
          <%= account.input :role_id, :as => :select, :collection => @roles %>
        <% end %>

    <%- end -%> <%# END f.inputs do %>
      <%= submit_tag 'Create User', :class => "button" %>
    <%- end -%> <%# END form %>
4

2 回答 2

0

知道了!!我删除了 :url => 并在 semantic_form_for 块中将 :user 更改为 @user ......我猜我的方式是导致 params[:account] 引发批量分配

于 2012-10-02T06:08:53.350 回答
-1

尝试将此添加到您的用户类

attr_accessible :accounts_attributes
于 2012-05-11T17:23:54.567 回答