2015-10-23 287 views
1

我想添加一个虚拟属性到一个activerecord对象。定义getter/setter很简单,但我希望我的属性出现在属性hash(和attribute_names等)中。由于这是rails 4,我不能使用attr_accessible。如何添加虚拟属性到属性哈希轨道4

我还需要添加什么更多的代码,以便我可以调用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 
+1

下要“属性出现”什么情况? 'attr_accessor'属性可以与'form_for'一起使用,并且可以在'.update()'中进行批量分配。 –

+0

质量分配和对.attributes的响应 –

+0

只需设置'attr_accessor:authors' –

回答

4
def attributes 
    super.merge({'authors' => authors}) 
end