Forum: Ruby on Rails ActiveRecord column with reserved name 'class'

483af713df3e9bb61253f7e54ec78365?d=identicon&s=25 Derek Mailer (mailerhq)
on 2008-01-11 10:40
I have a legacy database with a column named 'class' which is causing
Rails problems. Renaming the column isn't an option and the workarounds
I've seen so far don't suit.

I'm running rails 2.0.2 and an example of the error thrown looks like
this...
undefined method `generated_methods' for "ADD":String

c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/attribute_methods.rb:188:in
`method_missing'

(The value returned in the 'class' column is 'ADD' in this case.

Can anyone suggest a nice, neat, dry, satisfying solution?
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-01-11 11:07
(Received via mailing list)
On 11 Jan 2008, at 09:40, Derek Mailer wrote:

> c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/
> attribute_methods.rb:188:in
> `method_missing'
>

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

If I'm reading things right, that will stop AR from generating a class
method to read your attribute. You can still get at it via foo[:class]
(or define you own method returning read_attribute(:class)

Fred
483af713df3e9bb61253f7e54ec78365?d=identicon&s=25 Derek Mailer (mailerhq)
on 2008-01-11 13:27
Frederick Cheung wrote:

> How about
> class MyTable < AR:Base
>    class << self
>      def instance_method_already_implemented?(method_name)
>        return true if method_name == 'class'
>        super
>      end
>    end
> end
>
> If I'm reading things right, that will stop AR from generating a class
> method to read your attribute. You can still get at it via foo[:class]
> (or define you own method returning read_attribute(:class)

You're absolutely right and that'll ding dang do for me very nicely
thanks, Fred! I no longer have errors in all the places they were
showing before.

Just as a note to anyone else reading this post, you might need to
restart script/console rather than issue a reload! command after
implementing this fix.

Derek
C1a49731988f4e22051fee9c0b0ee047?d=identicon&s=25 Gabe H. (noreaster)
on 2008-08-19 19:38
The same thing worked for me as well. GORGEOUS!!  AHHHHHHH!!  I want to
go run around my office now.

Thank you so much for the help!!  AWESOME!
Dc45352908dbb9a4c9299c1ffe84ebf2?d=identicon&s=25 Brandon Joyce (brandonjoyce356)
on 2009-02-22 20:47
Worked great for me as well.  Thanks!
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.