开发者

Adding Variables to AR Object

开发者 https://www.devze.com 2022-12-12 17:32 出处:网络
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.

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.

  1. 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.

  2. 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"
    
0

精彩评论

暂无评论...
验证码 换一张
取 消