One way to dynamically add attributes to some model object on the fly
is to just directly add the new key(s)/val(s) to the model instance's
attributes:
$ ./script/console
Loading development environment (Rails 2.2.2)
>> test = Test.find(:first)
=> #<Test id: 1, name: "Abe">
>> test.attributes.keys
=> ["id", "name"]
>> test["favorite_color"] = 'blue'
=> "blue"
>> test.attributes.keys
=> ["id", "favorite_color", "name"]
>> test.favorite_color
=> "blue"
Another way, assuming the purpose is to add additional attribs coming
from a db qry, ... Note that any additional attribs returned from a
db query will be automatically added to the returned model ob(s):
>> test2 = Test.find_by_sql("select *, 'blue' as favorite_color from tests
>> order by id limit 1").first
=> #<Test id: 1, name: "Abe">
>> test2.attributes.keys
=> ["id", "favorite_color", "name"]
>> test2.favorite_color
=> "blue"
Note that neither of the above requires any accessor-related code in
your model ob (unless you want/need it for other purposes):
$ cat app/models/test.rb
class Test < ActiveRecord::Base
end
Jeff
On Feb 15, 3:54 pm, rapdup <[email protected]> wrote:
> I am trying to access a model's attribute that does not have a column
> in the model's corresponding table. It exists only through an
> attr_accessor:
>
> class Widget < ActiveRecord::Base
> attr_accessor :attribute_not_in_db
> end
>
> I can access the attribute directly:
>
> >> w = Widget.new(:attribute_not_in_db => "foo")
> >> w.attribute_not_in_db
>
> => "foo"
>
> However, I can't seem to access it other ways:
>
> >> attr_symbol = :attribute_not_in_db
> >> w[attr_symbol]
>
> => nil
>
> >> attr_name = "attribute_not_in_db"
> >> w[attr_name]
>
> => nil
>
> >> w.read_attribute(attr_symbol)
>
> => nil
>
> >> w.read_attribute(attr_name)
>
> => nil
>
> This is probably rather basic, but my searching hasn't turned up the
> answer. Any guidance would be apprecited.
>
> thx.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---