ciembor
ciembor

Reputation: 7337

Validate existence of submodel in 'has_one' relation

I have two models, one Post and Genre. I'm creating new post with given genre_id. What is the best way of validating if genre with given id exists? For now I'm validating presence of genre_id, but it's not enough.

validates :genre_id, presence: true

I know I can check whether the genre exists in a controller, but I would prefer to have this in my post validator object.

Upvotes: 0

Views: 612

Answers (1)

craig.kaminsky
craig.kaminsky

Reputation: 5598

You can explicitly tell Rails to validate the genre association and not just the attribute, genre_id with:

has_one :genre 
validates_presence_of :genre

validates_presence_of

Upvotes: 1

Related Questions