的ActiveRecord :: DangerousAttributeError

Jen*_*unt 14 activerecord ruby-on-rails ruby-on-rails-3

我必须连接到我们的freeradius服务器使用的现有数据库.一个表有一个名为属性的列,我试图访问.

访问时,我收到他的错误:

ActiveRecord::DangerousAttributeError 
attribute? is defined by ActiveRecord
Run Code Online (Sandbox Code Playgroud)

我试图在我的模型中选择并重命名此列:

def self.default_scope
    Radcheck.select("attribute as newattribute")
end
Run Code Online (Sandbox Code Playgroud)

但那也没有用.

任何人都可以推荐一种方法吗?我真的想在rails中重命名列!

The*_*tor 11

在类似的问题上我找到了这个答案:https://stackoverflow.com/a/9106597/1266906

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

gem 'safe_attributes'
Run Code Online (Sandbox Code Playgroud)

对你Gemfile和宝石将尝试自动处理所有碰撞的名称.

与其他答案一样,您需要使用Radcheck[:attribute]Radcheck.read_attribute :attribute/ Radcheck.write_attribute :attribute, 'value'访问具有内部保留名称的字段,但gem确保验证validates_presence_of :attribute将像往常一样工作.

有关详细信息,请访问https://github.com/bjones/safe_attributes

  • 只是Google员工的一个注释:这个gem几乎可以用于任何保留字*除了*属于`属性'.自述文件:"使用ActiveRecord时,在模式中几乎不可能有一个名为'attribute'的列." (2认同)

sar*_*ana 2

我从未遇到过这种情况,但我认为这应该可行

class Radcheck < ActiveRecord::Base
    default_scope :select=> 'attribute as newattribute'
end
Run Code Online (Sandbox Code Playgroud)

您应该使用实例方法 default_scope 而不是类一

您还可以选择使用实例方法,例如:

RadCheck.read_attribute :attribute
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你