0

我查看了很多与嵌套属性中的质量分配相关的问题,但没有一个能帮助我......

我正在使用 Devise 并有一个User具有不同类型的模型,例如Client

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation, :remember_me, :rolable_type
  belongs_to :rolable, :polymorphic => true
  accepts_nested_attributes_for :rolable
end

class Client < ActiveRecord::Base
  has_one :user, :as => :rolable
  attr_accessible :specialty, :address
end

我有以下表格用于创建具有客户端类型和客户端属性的新用户,并且正在工作:

[...]

  resource.rolable = child_class_name.constantize.new if resource.rolable.nil?

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

[...]

  <% # customized code begin %>
  <%= fields_for resource.rolable do |rf| %>
    <% if rolable_type == 'client' %>

    <div><%= rf.label :specialty %><br />
    <%= rf.text_field :specialty %></div>

[...]

    <% end %>
  <% end %>

  <%= hidden_field :user, :rolable_type, :value => rolable_type %>
  <% # customized code end %>

[...]

  <div><%= f.submit "Sign up" %></div>
<% end %>

我有以下用于编辑同一用户但不起作用:我收到以下错误ActiveModel::MassAssignmentSecurity::Error in UsersController#update::Can't mass-assign protected attributes: client

    <%= form_for(@user) do |f| %>
       <%= render 'shared/error_messages', object: f.object %>

[...]

      <% f.fields_for(@user.rolable) do |rf| -%>

        <div><%= rf.label :specialty %><br />
        <%= rf.text_field :specialty %></div>

        <div><%= rf.label :address %><br />
        <%= rf.text_field :address %></div>
      <% end %>

[...]

这是我的UsersController更新操作:

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end
4

2 回答 2

0

你需要一个 accept_nested_attributes_for :rolable 在用户类

请参阅:Rails 3.1:accepts_nested_attributes_for 和 has_one 关联 - 不起作用?

于 2013-06-11T05:41:16.437 回答
0

OP的解决方案。

我换<% f.fields_for(@user.rolable) do |rf| %><%= f.fields_for :rolable do |rf| %>

它奏效了

于 2018-04-30T14:48:35.577 回答