Non persistent ActiveRecord model attributes

后端 未结 5 1261
暗喜
暗喜 2020-12-10 00:20

I want to add to an existing model some attributes that need not be persisted, or even mapped to a database column. Is there a solution to specify such thing ?

5条回答
  •  渐次进展
    2020-12-10 01:00

    In my case I wanted to use a left join to populate custom attribute. It works if I don't add anything but I also want to be able to set the attribute on a new object and of course it doesn't exist. If I add attr_accessor then it always returns nil after a select. Here's the approach I've ended up with that works for setting on new object and retrieving from left join.

    after_initialize do
      self.foo = nil unless @attributes.key?("foo")
    end
    
    def foo
      @attributes["foo"]
    end
    
    def foo=(value)
      @attributes["foo"] = value
    end
    

提交回复
热议问题