简体   繁体   English

rails:在创建过程中尝试设置STI类型时无法大规模分配这些受保护的属性

[英]rails: can't mass assign to these protected attributes while trying to set STI type during create

I have just started out learning rails and ruby, so please bear with me if this is too dumb. 我刚开始学习Rails和红宝石,所以如果这太愚蠢,请多多包涵。

There are several different AppModule types in my app, which have different behavior but similar data, so I save them using single table inheritance. 我的应用程序中有几种不同的AppModule类型,它们的行为不同但数据相似,因此我使用单表继承来保存它们。

However when trying allow the user to explicitly select which type they want in app_modules/new.html.erb I get the warning WARNING: Can't mass-assign these protected attributes: type . 但是,当尝试允许用户在app_modules/new.html.erb显式选择他们想要的类型时,我收到WARNING: Can't mass-assign these protected attributes: type Here is the relevant code: 以下是相关代码:

<% form_for(@app_module) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :type %><br />
    <%= f.select( :type, options_from_collection_for_select(AppModule.subclasses().map{ |c| c.name}, 'to_s', 'to_s')) %>
    </p>

  <%= f.submit 'Create' %>
 <% end %>

I have tried explicity setting attr_accessible :type in the model file but it didn't work 我已经尝试在模型文件中显式设置attr_accessible :type ,但是没有用

I am using rails 2.3.8 and ruby 1.8.7. 我正在使用rails 2.3.8和ruby 1.8.7。

Any help greatly appreciated, thanks... 非常感谢任何帮助,谢谢...

You shouldn't ever have to set the type attribute manually. 您永远不必手动设置type属性。 Use the subclasses you created instead. 请改用您创建的子类。

model = params[:app_module].delete(:type).constantize
model = AppModule unless model.is_a?(AppModule)
@app_module = model.new(params[:app_module])

Add this to your base class: 将此添加到您的基类:

  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end

I recommend Adam's method unless you are dealing with a mixed list. 我建议使用亚当的方法,除非您要处理混合列表。

我只需要在“ config / application.rb”中的以下行中注释即可解决此问题。

# config.active_record.whitelist_attributes = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM