[英]How Do I Add A Virtual Attribute To The Attributes Hash in Rails 4
I want to add a virtual attribute to an activerecord object. 我想将虚拟属性添加到activerecord对象。 It's straightforward to define the getter/setter but I want my attribute to appear in the attributes hash (and attribute_names etc..). 定义getter / setter很简单,但是我希望我的属性出现在属性哈希(和attribute_names等)中。 Since this is rails 4 I can't use attr_accessible. 由于这是rails 4,因此无法使用attr_accessible。
What more do I need to add to this code so I can call reference.attributes and have the value of authors show up there? 我还需要在此代码中添加什么,以便可以调用reference.attributes并在其中显示作者的价值?
class Reference < ActiveRecord::Base
def authors
self.author_names.to_a.join(' and ')
end
def authors=(val)
self.author_names.destroy
val.strip.split(/(?:[ ]and[ ])|\;/).each {|entry|
self.author_names << AuthorName.new(name: entry)
}
end
end
def attributes
super.merge({'authors' => authors})
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.