ruby-on-rails-5 – 轨道中Virtus的默认值

我正在使用带有rails(5.0.2)的virtus(1.0.5).我使用Virtus作为模型,因为它具有基于被访问页面的验证.

我的组织模型是

class Organization < ApplicationRecord
  validates :name,presence: true
end

和使用virtus创建的表单是

class OrganizationProfileForm
  include ActiveModel::Model
  include Virtus.model

  attribute :call_center_number,String,default: :org_call_center_number

  validates :call_center_number,presence: true

  def initialize(organization)
    @organization = organization
  end

  private

  def org_call_center_number
    @organization.call_center_number
  end

end

不幸的是,上面的代码不起作用

Loading development environment (Rails 5.0.2)
2.3.0 :001 > of = OrganizationProfileForm.new(Organization.last)
Organization Load (0.6ms)  SELECT  "organizations".* FROM "organizations" ORDER BY "organizations"."id" DESC LIMIT $1  [["LIMIT",1]]
=> #<OrganizationProfileForm:0x007f9d61edd6a8 @organization=# <Organization id: 1,name: "Some name",call_center_number: "4892374928",created_at: "2017-03-29 09:35:22",updated_at: "2017-03-29 09:37:59">>
2.3.0 :002 > of.call_center_number
=> nil

解决方法

我们需要在initialize方法调用super().

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...