Adding Variables to AR Object
How can I add a variable to a set of objects 开发者_如何学Creturned by ActiveRecord? I've looked around and none of the methods I've seen seem to work.
Thanks in advance!
The question is vague and can be interpreted in a couple of ways.
Adding a variable to a list.
list_of_objects_returned_by_activeRecord << variable
This seems too simple and is probably not what you're looking for.
Adding a variable to each item in the list.
Assuming your talking about instances of models, the simplest way is to add an attr_accessor to your model.
class Model < ActiveRecord::Base ... attr_accessor :new_attribute end
You probably want to set it to some value whenever the model is loaded so you want to add an after_initialize method to the model.For example, the following will add a nick_name attribute for every user loaded and default it to their first_name suffixed with "-O".
class User < ActiveRecord::Base ... attr_accessor :nick_name def after_initialize self.nick_name = first_name + "-O" end end @user = User.first @user.first_name # => "Steve" @user.nick_name # => "Steve-O" @user.nick_name = "Tiny" # sets nick_name to "Tiny". @user.first_name # => Still "Steve"
精彩评论