gpt4 book ai didi

ruby-on-rails-5 - Rails 中 Virtus 的默认值

转载 作者:行者123 更新时间:2023-12-04 07:10:48 26 4
gpt4 key购买 nike

我正在将 virtus(1.0.5) 与 rails (5.0.2) 一起使用。我将 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() 。

关于ruby-on-rails-5 - Rails 中 Virtus 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com