Reputation: 45
I have this model that validates presence: true
for both post_id
and user_id
but I want it to validate the presence of one if the other is absent.
here is the validation :
validates :user_id, :comment_id, :post_id, presence: true
If you have any questions don't hesitate to ask
Upvotes: 1
Views: 990
Reputation: 21
Simple Update thanks to rubocop, when i tried to use this logic, rubocop auto correct my line actually
C: [Corrected] Rails/Validation: Prefer the new style validations validates :column, presence: value over validates_presence_of. validates_presence_of :<model_name>, unless: :
it basically converted this version
validates_presence_of :<model_name>, unless: :<condition>
To this:
validates :<model_name>, presence: { unless: :<condition> }
Upvotes: 0
Reputation: 3139
validates_presence_of :post_id, unless: :user_id
validates_presence_of :user_id, unless: :post_id
Upvotes: 1
Reputation: 2398
Since ActiveRecord automatically creates question mark methods for each of your model's attributes, you could also do:
validates_presence_of :post_id, unless: :user_id?
validates_presence_of :user_id, unless: :post_id?
:post_id?
or user_id?
returns false for nil or blank.
Upvotes: 0