首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails中Virtus的默认值

rails中Virtus的默认值
EN

Stack Overflow用户
提问于 2017-03-29 10:13:32
回答 2查看 583关注 0票数 4

我使用virtus(1.0.5)和rails (5.0.2)。我使用Virtus作为一个模型,因为它具有基于所访问的页面的验证。

我的组织模式是

代码语言:javascript
复制
class Organization < ApplicationRecord
  validates :name, presence: true
end

使用virtus创建的表单如下

代码语言:javascript
复制
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

不幸的是,上面的代码不能工作

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-10 06:08:58

我们需要在初始化方法中调用super()。

票数 1
EN

Stack Overflow用户

发布于 2017-04-06 19:51:15

尝试删除行private,因为这可能会阻止对方法org_call_center_number的调用。为维塔斯上的默认值提供的示例使用的是公共实例方法,而不是私有实例方法。

请参阅:“私人”、“公共”和“受保护的方法”有什么区别?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43090600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档