This validation appears to work as expected:
validates_uniqueness_of :goal_type, scope: [:goal_length, :user_id], conditions: -> { where(is_complete: false) }
Pregunta
My model, Goal
, has these three attributes: goal_type
, goal_length
, and is_complete
.
Goal
belongs_to :user
.
goal_type
can only be "X", "Y", or "Z"
goal_length
can only be "short", "mid", or "long"
is_complete
can be true or false
I want there to only ever be one Goal
(validates_uniqueness_of
) with a specified goal_length
and goal_type
when looking at Goals that both belong to the same user and have is_complete set to false
Plain english examples:
If a user has a short
X
goal that they have not yet completed, they cannot create a new short
X
goal.
If a user has a short
X
goal that they have completed, they can create a new short
X
goal.
This validation works, but does not check if the existing goals have their is_complete
attribute set to true. If is_complete
is true on the previously existing models, it is ok to create a new goal with the same attributes:
validates_uniqueness_of :goal_type, scope: [:goal_length, :user_id]
How would I add a check for the condition where the validation is ignored if the matching previous goal has is_complete set to true ?
Solución
This validation appears to work as expected:
validates_uniqueness_of :goal_type, scope: [:goal_length, :user_id], conditions: -> { where(is_complete: false) }