How to add new attribute to ActiveRecord

后端 未结 8 1905
佛祖请我去吃肉
佛祖请我去吃肉 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:39

    I met the same issue. and successfully bypass using instance_eval

    @test.all
    
    @test.each do |elm|
      elm.instance_eval { @newatt = 'added string' }
    end
    

    normally it doesn't run into issue, when use attr_accessor. it appears when other DSL override "newattr=" which cause the issue. In my case, it's money-rails "monetize :newatt"

    Explicitly use write_attribute doesn't work as it is the reason to raise exception in rails 4.x

提交回复
热议问题