【问题标题】:Why can not I use the word attribute a table with the column name as Ruby on Rails?为什么我不能在列名称为 Ruby on Rails 的表中使用单词属性?
【发布时间】:2015-11-07 09:48:34
【问题描述】:

我只是 rails g scaffold test name:string attribute:string value:string 使用了这个命令。

但是当我保存填写表格时,我得到了活动记录器属性列的错误。

根据我的研究 gem 'safe_attributes' gemfile,它解决了这个问题。我做了安装。

这次是在 Tests#new 中的 NoMethodError

private method 'attribute' 调用错误。

提取的源代码(大约第 20 行):

<% = f.text_field :attribute %>

我该如何解决这个问题?你能帮助我吗。

【问题讨论】:

标签: ruby-on-rails database activerecord attributes


【解决方案1】:

问题是已经定义了私有方法attribute 由于我们通过method_missing 访问模型字段,当您尝试调用Test#attribute 时,您将获得私有方法

attribute 方法定义在这里:https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods/read.rb#L82

为避免此问题,请勿使用与已定义方法同名的模型属性。

【讨论】:

  • 我添加了指向方法定义的链接。所以你不能用它作为属性名。
  • @EmrahYıldırım 每种语言和框架都有您无法使用的关键字。您可以追求编程以外的其他东西或克服它,就是这样。
猜你喜欢
  • 2013-08-22
  • 1970-01-01
  • 2015-01-12
  • 2014-08-26
  • 2015-04-16
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 2013-09-25
相关资源
最近更新 更多