2011-11-15 86 views
2

我已经有一些使用列名attribute的表的现有数据库。我无法改变这个名字,因为这意味着重新编译我们的整个应用程序。ActiveRecord :: DangerousAttributeError - 属性?由ActiveRecord定义

当试图访问数据库,我结束了:

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 

但是,这是凌乱而乱搞我当我真正TR y并进入桌面...

我的其他选择是什么 - 有没有什么好的方法绕着这个小小的玩具?

+0

也许这个问题的解决方案可以帮助你:http://stackoverflow.com/questions/5428987/how-can-i-use-activerecord-on-a-database-that-has-a-column-named -attribute-d – JofoCodin

+0

这个也可以帮助你:http://stackoverflow.com/questions/4348037/overriding-or-aliasing-name-of-column-in-legacy-database-using-rails-activerecor – sparrovv

+0

I以前试过这个:@radcheck = Radcheck.all(:select =>'attr'属性)。但我仍然得到一个错误:( –

回答

3

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

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

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

我仍然无法实际使用属性。

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

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

无需担心的ActiveRecord的保留属性,只需添加一个宝石在你的Gemfile和创业板将自动完成名称冲突的。

gem 'safe_attributes' 

享受栏杆..

3

而不必关心哪些属性是通过ActiveRecord的Rails中3.0保留只需添加

gem 'safe_attributes' 

到你的Gemfile和创业板会尽量照顾所有名称都会自动碰撞。