Rails:在创建期间尝试设置 STI 类型时无法批量分配给这些受保护的属性

发布于 2024-10-02 19:22:22 字数 718 浏览 0 评论 0原文

我刚刚开始学习 Rails 和 ruby​​,所以如果这太愚蠢了,请耐心等待。

我的应用程序中有几种不同的 AppModule 类型,它们具有不同的行为但相似的数据,因此我使用单表继承来保存它们。

但是,当尝试允许用户在 app_modules/new.html.erb 中明确选择他们想要的类型时,我收到警告警告:无法批量分配这些受保护的属性:类型.这是相关代码:

<% 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 %>

我尝试在模型文件中显式设置 attr_accessible :type 但它不起作用

我使用的是 Rails 2.3.8 和 ruby​​ 1.8.7。

非常感谢任何帮助,谢谢...

I have just started out learning rails and ruby, so please bear with me if this is too dumb.

There are several different AppModule types in my app, which have different behavior but similar data, so I save them using single table inheritance.

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. 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

I am using rails 2.3.8 and ruby 1.8.7.

Any help greatly appreciated, thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

万劫不复 2024-10-09 19:22:23

将其添加到您的基类中:

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

我推荐 Adam 的方法,除非您正在处理混合列表。

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.

不再让梦枯萎 2024-10-09 19:22:23

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

# config.active_record.whitelist_attributes = true

I just need to comment following line in my 'config/application.rb' to solve this issue.

# config.active_record.whitelist_attributes = true
秋心╮凉 2024-10-09 19:22:22

您不必手动设置 type 属性。请改用您创建的子类。

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

You shouldn't ever have to set the type attribute manually. 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])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文