0

There's a field in my resource that I want to set to 1 if it's nil in the model. I have the following code, but the resource is still producing minimum_approvers: nil

Any ideas on what's going on?

module V1
  class EntityResource < BaseResource
    model_hint model: Entity

    attribute :logo
    attribute :minimum_approvers

    def minimum_approvers
      @model.minimum_approvers.nil? ? 1 : @model.minimum_approvers
    end
Mirror318
  • 11,875
  • 14
  • 64
  • 106

2 Answers2

0

If the method you want to call has the same name as the model's attribute, you can't override it. The best you can do is make a method in the model that does the logic, then call the method in your resource.

Mirror318
  • 11,875
  • 14
  • 64
  • 106
  • this is one of the reasons why I prefer `fast_jsonapi` - doing things the Rails way results in more productivity for the developers.. – Tilo Dec 16 '18 at 19:44
  • btw. even defining the method in the model does not seem to work – Tilo Dec 16 '18 at 22:38
0

Just to flesh out the answer by @Mirror318 and to respond to the comment by @Tilo, the following worked for me with V0.10.7 of jsonapi-resources:

module V1
  class Entity < ApplicationRecord
    def minimum_approvers_with_default
      minimum_approvers || 1
    end
  end
end

module V1
  class EntityResource < BaseResource
    attribute :minimum_approvers,
              delegate: :minimum_approvers_with_default
  end
end
Andreas Gebhard
  • 361
  • 2
  • 8