How can I use ActiveRecord on a database that has a column named 'attribute'? (DangerousAttributeError)
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 =&g开发者_运维技巧t; 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
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"
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
Maybe you can use alias_attribute and thus use methods with different names.
精彩评论