如何向 ActiveRecord 添加新属性 [英] How to add new attribute to ActiveRecord
问题描述
从模型中获取所有值后,我想向 ActiveRecord 类添加另一个自定义属性(此属性不是 db 中的列),以便我可以在视图中使用它,但 Rails 不允许我添加一个.我应该在它的模型类中添加什么?
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 rails does not allow me to add one. What should I add in its model class?
@test.all
@test.each do |elm|
elm[:newatt] = 'added string'
end
错误:
can't write unknown attribute `newatt'
推荐答案
试试这个
class Test < ActiveRecord::Base
attr_accessor :newattr
end
你可以像访问它
@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.
这篇关于如何向 ActiveRecord 添加新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!