How to add new attribute to ActiveRecord

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

    try this

    class Test < ActiveRecord::Base
      attr_accessor :newattr
    end
    

    you can access it like

    @test = Test.new
    @test.newattr = "value"
    

    As you may notice this a property, not a hash. so it uses . syntax. however, if you need it to behave like an hash you can do this without defining a new attribute

    @test.all
    @test.each do |elm|
        new_elm = {}
        new_elm[:newatt] = 'added string'
    end
    

    Lastly, I am not exactly sure what you are trying to do. if this doesn't make sense to you, kindly rephrase your question so we can understand the problem better.

提交回复
热议问题