简体   繁体   English

如何在Rails 4的属性哈希中添加虚拟属性

[英]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.

相关问题 如何在Rails上的ruby中的nested_attributes哈希中添加额外的属性? - How to add an extra attribute in nested_attributes hash in ruby on rails? 将Rails 5属性api与哈希虚拟属性结合使用 - Using Rails 5 attributes api with hash virtual attributes 如何在Rails中为模型的哈希属性创建客户序列化程序? - How do I create a customer serializer for a hash attribute of a model in Rails? 如何在 Ruby on Rails 中为模型添加虚拟属性? - How to add a virtual attribute to a model in Ruby on Rails? 具有多个对象属性的Rails Hash。 如何保存它们? - Rails Hash with several object attributes. How do I save them all? 我如何在Ruby on Rails中实现的CakePHP(使用代码,而不是SQL)中实现虚拟属性 - How do I achieve virtual attributes in CakePHP (using code, not SQL) as implemented in Ruby on Rails 虚拟属性Rails - 未知属性错误 - Virtual attributes Rails - Unknown Attribute Error Rails 3动态添加虚拟属性 - Rails 3 add virtual attribute dynamically 如何使用 rails 中的表单向属性添加整数? - How do I add an integer to an attribute using a form in rails? 如何将数据属性添加到R​​ails radio_button? - How do I add a data attribute to a Rails radio_button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM