masnion
masnion

Reputation: 45

how to validate presence of element in absence of another in rails

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

Answers (3)

Caner Taşan
Caner Taşan

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

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

validates_presence_of :post_id, unless: :user_id
validates_presence_of :user_id, unless: :post_id

Upvotes: 1

John Baker
John Baker

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

Related Questions