使用具有多个角色的Devise用户的fields_for表单中的批量分配错误

时间:2013-06-11 04:11:32

标签: ruby-on-rails forms nested-forms mass-assignment

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

我正在使用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#updateCan'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

2 个答案:

答案 0 :(得分:0)

你需要在User class

中使用accepts_nested_attributes_for:rolable

请参阅:Rails 3.1: accepts_nested_attributes_for and has_one association - won't work?

答案 1 :(得分:0)

OP解决方案。

我为({:a 1 :b ["red" "blue"]} {:a 2 :b ["green"]} {:a 1 :b ["yellow"]} {:a 2 :b ["orange"]}) 更改了({:a 1 :b ["red" "blue" "yellow"]} {:a 2 :b ["green" "orange"]})

它有效