Ruby-on-rails Rails 错误:无法批量分配受保护的属性:interest_ids?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10560458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:23:30  来源:igfitidea点击:

Rails Error: Can't mass-assign protected attributes: interest_ids?

ruby-on-railsassociations

提问by js111

Im working with a multistep form (using Wicked gem). In the first couple steps of the form i am editing the user model and those steps work fine.. Then I attempt the "interests" model which has a HABTM relationship with the user model. However i get this error:

我使用多步表单(使用 Wicked gem)。在表单的前几个步骤中,我正在编辑用户模型,这些步骤工作正常。然后我尝试使用与用户模型具有 HABTM 关系的“兴趣”模型。但是我收到这个错误:

ActiveModel::MassAssignmentSecurity::Error in UserStepsController#update

Can't mass-assign protected attributes: interest_ids
Rails.root: /Users/nelsonkeating/rails_projects/Oreminder1

Application Trace | Framework Trace | Full Trace
app/controllers/user_steps_controller.rb:12:in `update'

user_steps_controller.rb

user_steps_controller.rb

 class UserStepsController < ApplicationController
  include Wicked::Wizard
  steps :standard, :personal, :interests, :dates 

 def show
   @user = current_user
   render_wizard
 end

 def update
  @user = current_user
  @user.attributes = params[:user]
 render_wizard @user
end

end

Heres the view:

这是视图:

<%= render layout: 'form' do |f| %>

<% for interest in Interest.find(:all) %>
 <label class="checkbox">
  <%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %>
  <%= interest.name %>
 </label>
<% end %>

<% end %>

Any ideas? Thanks!

有任何想法吗?谢谢!

回答by Mischa

You can get rid of this error by adding this to your user model:

您可以通过将其添加到您的用户模型来消除此错误:

attr_accessible :interest_ids

Without this the interest_idsattribute is protected against mass assignmentand when you try to assign values to it anyway an exception is thrown.

如果没有这个,该interest_ids属性将受到保护以防止大量分配,并且当您尝试为其分配值时,无论如何都会引发异常。