rails 中 Virtus 的默认值
default values for Virtus in rails
我正在使用带有 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 [["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
尝试删除行 private
,因为这可能会阻止对方法 org_call_center_number
的调用。 Virtus repo 上的默认值示例使用 public 实例方法,而不是私有方法。
参见:What are the differences between "private", "public", and "protected methods"?
我们需要在initialize方法中调用super()
我正在使用带有 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 [["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
尝试删除行 private
,因为这可能会阻止对方法 org_call_center_number
的调用。 Virtus repo 上的默认值示例使用 public 实例方法,而不是私有方法。
参见:What are the differences between "private", "public", and "protected methods"?
我们需要在initialize方法中调用super()