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

你。 提交于 2019-12-22 14:02:23

问题


I am accessing a database that I can't change and it has a column named attribute defined. Anytime I try to access an attribute, I get this exception:

attribute? is defined by ActiveRecord(ActiveRecord::DangerousAttributeError)

my code:

class User < ActiveRecord::Base
      def self.authenticate(username,password)
        where(:username => username, :value => password).first
      end
end

I found a plan on the ruby on rails mailing list for fix the problem but not work for me

  class << self
    def instance_method_already_implemented?(method_name)
      return true if method_name == 'attribute'
      super
    end
  end

I'm not sure if it matters, but here are the details of my environment:

  • ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.4.0]
  • Rails
  • 3.0.1 activerecord (3.0.1) activeresource (3.0.1)

UPDATE(solved):

PLAN A:

select("username, value").where(:username => username, :value => password).first

回答1:


ActiveRecord queries support the :select parameter, which lets you define the fields you want returned to you as a string.

Usually people use something like:

:select => 'field1, field2'

If you know the raw query language for your database server, then you can use that in the select string. One of the options when selecting fields using SQL is to use the as modifier:

select field1 as the_first_field, field2 as the_second_field

and the database will return the fields using the new field names instead of the old field names. It's an easy way to manage legacy fields that are named in ways that conflict with Rails if your database supports that.

See "Learn to Love ActiveRecord's :select Parameter" in "Five ActiveRecord Tips" and "Selecting Specific Fields" in the Ruby on Rails Guides.

Here's an example from one of my Rails apps using the rails console to access my Postgres DB:

ruby-1.9.2-p180 :007 > dn = DomainName.first
 => #<DomainName id: 1, domain_name: "ip72-208-155-230.ph.ph.cox.net", created_at: "2010-04-20 05:53:22", updated_at: "2010-04-20 05:53:22"> 
ruby-1.9.2-p180 :008 > dn = DomainName.first(:select => 'id, domain_name as dn')
 => #<DomainName id: 1> 
ruby-1.9.2-p180 :009 > dn['id']
 => 1 
ruby-1.9.2-p180 :010 > dn['dn']
 => "ip72-208-155-230.ph.ph.cox.net"



回答2:


For column x, ActiveRecord creates x, x=, and x? methods. So, update your fix to this:

class << self
    def instance_method_already_implemented?(method_name)
        return true if method_name == 'attribute?'
        super
    end
end



回答3:


Maybe you can use alias_attribute and thus use methods with different names.



来源:https://stackoverflow.com/questions/5428987/how-can-i-use-activerecord-on-a-database-that-has-a-column-named-attribute-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!