How can I use ActiveRecord on a database that has a column named 'valid'? (DangerousAttributeError)

做~自己de王妃 提交于 2019-11-27 22:55:00

Try this:

class MyTable < AR:Base
   class << self
     def instance_method_already_implemented?(method_name)
       return true if method_name == 'valid'
       super
     end
   end
end

It's a hack, and it might not work in rails 3, but it could fix the problem for now.

I found it on the ruby on rails mailing list

If you wanted, you could also look at datamapper, which handles these sort of things somewhat more sanely.

Use safe_attributes - https://github.com/bjones/safe_attributes . It works perfectly out of the box:

class WebsiteUser < ActiveRecord::Base
    establish_connection 'cf_website'
    set_table_name 'nc_users'
    bad_attribute_names :hash    
end

Without worrying about ActiveRecord's reserved attributes, just add a gem in your gemfile and the gem will take care of name collisions automatically.

gem 'safe_attributes'

http://goo.gl/OO2H7

For reads you might be able to use SQL's select-as statement. Not sure if the following will work, but a default scope may make this easily do-able.

class MyRecord < ActiveRecord::Base
    default_scope :select=> 'valid as valid_column'
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!