4

I am using virtus(1.0.5) with rails (5.0.2). I am using Virtus for a model since it has validations based on the page being accessed.

My Organization model is as

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

and form created using virtus is as

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

Unfortunately, the above code doesn't work

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
Prasad Surase
  • 6,486
  • 6
  • 39
  • 58

2 Answers2

1

We need to call super() in the initialize method.

Prasad Surase
  • 6,486
  • 6
  • 39
  • 58
0

Try removing the line private, as this may be preventing the call to the method org_call_center_number. The example given for default values on the Virtus repo uses a public instance method, not a private one.

See: What are the differences between "private", "public", and "protected methods"?

Community
  • 1
  • 1
anothermh
  • 9,815
  • 3
  • 33
  • 52