在嵌套模型轨道3.2中获取属性



我有两个模型user和profile
我想将用户名和密码保存在中的用户和其他用户配置文件详细信息中个人资料
现在,
用户模型具有:

has_one :profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password,:profile_attributes

配置文件模型具有

 belongs_to :user
 attr_accessible :firstname, :lastname

用户控制器具有

 def new
    @user = User.new
    @profileattr = @user.build_profile
  end
  def create
    @user = User.new(params[:user])
    if @user.save
      redirect_to root_url, :notice => "user created successfully!"
    else
      render "new"
    end
  end

视图new.html.erb包含用户和配置文件的字段
视图具有:

<%= form_for @user do |f| %>
  <% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>

  <%= f.fields_for @profileattr do |pf|%>
  <p>
    <%= pf.label :firstname %><br />
    <%= pf.text_field :firstname %>
  </p>
  <p>
    <%= pf.label :lastname %><br />
    <%= pf.text_field :lastname %>
  </p>
  <% end %>
  <p class="button"><%= f.submit %></p>
<% end %>

但是,当我运行此web应用程序时,它显示错误:

无法批量分配受保护的属性:配置文件

在调试时,我发现用户具有以下属性:

 :email:abc@gmail.com
 :password:secret
 :profile
            ---:firstname:abc
            ---:lastname:xyz

因此,视图返回的不是预期的params[:profile_attributes]
导致批量分配错误。那么出了什么问题?

你试过吗

  <%= f.fields_for :profile do |pf|%>

最新更新