How to add new attribute to ActiveRecord

后端 未结 8 1925
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-20 01:18

After getting all values from model, I want to add another custom attribute to the ActiveRecord class (this attribute is not a column in db) so that I could use it in view, but

8条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 01:34

    I think you mean to assign @test to the ActiveRecord query, correct? Try:

    @test = MyARClass.select("*, NULL as newatt")
    @test.each {|t| t[:newatt] = some_value}
    

    Another related solution is to make it a singleton class method, though you'd have to jump though more hoops to make it writeable and I intuitively feel like this probably incurs more overhead

    @test = MyARClass.all
    @test.each do t
      def t.newatt
        some_value
      end
    end
    

    Using the second method, of course you'd access it via @test.first.newatt, rather than @test.first[:newatt]. You could try redefining t.[] and t.[]=, but this is starting to get really messy.

提交回复
热议问题