Значения по умолчанию для Virtus в рельсах

Я использую virtus(1.0.5) с рельсами (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

2 ответа

Решение

Нам нужно вызвать super() в методе initialize.

Попробуйте удалить строку private, так как это может препятствовать вызову метода org_call_center_number, В примере, приведенном для значений по умолчанию в репозитории Virtus, используется метод открытого экземпляра, а не частного.

Смотрите: в чем различия между "приватными", "публичными" и "защищенными методами"?

Другие вопросы по тегам