ActiveRecord :: DangerousAttributeError - 属性?由ActiveRecord定义

时间:2011-11-15 22:17:26

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

我有一个现有的数据库,其中包含一些使用列名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

但是当我真正尝试访问桌子时,那很麻烦并且弄乱了我......

我的其他选择是什么?围绕这个小虫子有什么好方法吗?

3 个答案:

答案 0 :(得分:3)

我自己会回答这个问题,因为以上内容并没有完全解决。

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

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

我仍然无法使用属性。

最后,我用this excellent gem, safe_attributes,来做这个伎俩。现在我可以打电话:

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

答案 1 :(得分:3)

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

gem 'safe_attributes'

享受RAILING ..

答案 2 :(得分:3)

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

即可
 gem 'safe_attributes'

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

相关问题