Reputation: 2953
I am working on a rails app and want to validate some fields based on enum
. This is what I tried. But am getting some errors
class Listing < ActiveRecord::Base
enum status: [:draft, :published]
scope :draft, -> { where status: :draft }
scope :published, -> { where status: :published }
validates_presence_of :attribute1, :attribute2, :attribute3, unless: "status.draft?", on: :update
def publish!
self.update status: :published
end
end
All my status
fields have a default value of 0
which will be draft
. When I update
a listing am getting this error.
undefined method `draft?' for "draft":String
Its happening during the @listing.update(params)
. Could someone tell me what am doing wrong here?
Upvotes: 0
Views: 503
Reputation: 1602
When you call enum method, you should not call method from status
. just call from object.
It means that do not call @listing.status.draft?
, call @listing.draft?
so, do unless: 'draft?'
instead of unless: 'status.draft?'
and also you do not need to define scope for status. It automatically define scope methods for enum.
Read doc: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html
Upvotes: 2