Search code examples
ruby-on-railsvalidationruby-on-rails-4modelhas-one

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.


Solution

  • 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