Reputation: 2279
I have a rails application where Activity is one of the resources with the following attributes:
I want to create a new record for activity with status "in progress", given there is no existing activity with the same status. I believe this can be done using model validation, but being new to rails I have no idea how.
Upvotes: 1
Views: 33
Reputation: 2860
If status
is a enum
you may do:
class Activity < ApplicationRecord
enum status: [ :in_progress, :complete ]
validates_uniqueness_of :status, if: :in_progress?
end
This validation restricts you have only one activity
with in_progress
status.
Also if status
is a string you may do:
class Activity < ApplicationRecord
validates_uniqueness_of :status, if: proc { |activity| activity.status == 'in_progress' }
end
Upvotes: 1