AR: column methods?

In a model, it seems that methods for column access are only created
when one column method on an object is accessed. So, how can one
override the default column methods?

For instance:
create_table “dogs”, :force => true do |t|
t.column “color”, :string
end
create_table “tails”, :force => true do |t|
t.column “dog_id”, :integer, :null => false
t.column “color”, :string
end

If a dog’s tail indicates its own color, I want to use it. Otherwise,
the tail’s color is the same as the dog’s color:

class Dog < AR::Base
has_one :tail
end
class Tail < AR::Base
belongs_to :dog

alias_method :tail_color, :color
def color
return tail_color if tail_color != nil
return dog.tail_color
end
end

The trouble is that the ‘color’ method doesn’t exist yet:
$ ./script/console
Loading development environment.

x = Tail.new
NameError: undefined method color' for classTail’
from script/…/config/…/config/…/app/models/tail.rb:4:in
`alias_method’

Is there a way to force pre-defining of column methods so I can redefine
them?

I’m sure I’ve done something similar in the past.

Maybe try alias in place of alias_method…

alias :tail_color :color
def color … end

Does that make any difference (I am unable test at present)?

Chris

No… that was actually what I attempted first. I get the same error.

Chris R. wrote:

I’m sure I’ve done something similar in the past.

Maybe try alias in place of alias_method…

alias :tail_color :color
def color … end

Does that make any difference (I am unable test at present)?

Chris

In case someone else was looking for this: you can get to the raw data
using read_attribute(…) or the short form: self[:color]

e.g.
class Dog <…
def color
self[:color] || dog[:color]
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs