2015-10-23 121 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