【问题标题】:ActiveRecord::DangerousAttributeError - attribute? is defined by ActiveRecordActiveRecord::DangerousAttributeError - 属性?由 ActiveRecord 定义
【发布时间】:2011-11-15 22:17:26
【问题描述】:

我有一个现有的数据库,其中包含一些使用列名attribute 的表。我根本无法更改此名称,因为这意味着重新编译我们的整个应用程序。

当尝试访问数据库时,我最终得到:

attribute? is defined by ActiveRecord

首先我尝试使用 datamapper,但我无法继续使用它,我发现自己正在修复不应该被破坏的东西 - 比如嵌套属性....

所以,我回到了 ar 并使用它来解决问题:

class Radcheck < ActiveRecord::Base
  set_table_name 'radcheck'
  class << self
       def instance_method_already_implemented?(method_name)
         return true if method_name == 'attribute?'
         return true if method_name == 'attribute_before_type_cast'
         return true if method_name == 'attribute='
         return true if method_name == 'attribute'
         return true if method_name == 'attribute_changed?'
         return true if method_name == 'attribute_change'
         return true if method_name == 'attribute_will_change!'
         return true if method_name == 'attribute_was'
         return true if method_name == 'attribute_column'
         return true if method_name == 'reset_attribute!'
         super
       end
   end
end

但这很乱,当我真正尝试访问表格时,这让我很困惑......

我的其他选择是什么 - 有什么好办法绕过这个小混蛋?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

我将自己回答这个问题,因为上述问题并没有完全解决。

尽管重命名了我的控制器中的列:

 @radcheck = Radcheck.find(:all, :select => 'attribute AS attr')

我还是不能真正使用属性。

最后,我使用了this excellent gem, safe_attributes, 来解决问题。现在我可以用这个打电话了:

<% @radcheck.each do |radcheck| %>
<%= radcheck.attr %>
<% end %>

【讨论】:

    【解决方案2】:

    不用担心 ActiveRecord 的保留属性,只需在您的 gemfile 中添加一个 gem,gem 就会自动处理名称冲突。

    gem 'safe_attributes'
    

    享受栏杆..

    【讨论】:

      【解决方案3】:

      在 Rails 3.0 中无需关心 ActiveRecord 保留了哪些属性,只需添加

       gem 'safe_attributes'
      

      到您的 Gemfile,gem 将尝试自动处理所有冲突的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        相关资源
        最近更新 更多