我有一个现有的数据库,其中包含一些使用列名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但这很混乱,当我实际尝试访问该表时,它会困扰我……
我的其他选择是什么--有什么好办法绕过这个小麻烦吗?
发布于 2011-11-18 05:38:10
我将自己回答这个问题,因为上面的问题并没有完全解决。
尽管在我的控制器中重命名了列:
@radcheck = Radcheck.find(:all, :select => 'attribute AS attr')我仍然不能实际使用属性。
最后,我使用this excellent gem, safe_attributes,完成了这项工作。现在我可以用下面的代码调用:
<% @radcheck.each do |radcheck| %>
<%= radcheck.attr %>
<% end %>发布于 2012-12-07 19:03:46
不用担心ActiveRecord的保留属性,只需在您的gemfile中添加一个gem,gem就会自动处理名称冲突。
gem 'safe_attributes'享受RAILing..
发布于 2012-12-08 13:11:42
不必关心在Rails3.0中哪些属性是由ActiveRecord保留的,只需添加
gem 'safe_attributes'添加到你的Gemfile中,gem会自动处理所有冲突的名字。
https://stackoverflow.com/questions/8143954
复制相似问题