Search code examples
ruby-on-railsrubyvalidationassociationsmodel-associations

How to validate a table in Rails using another table


Using Ruby associations, I have two models that are associated to each other

class Event < ActiveRecord::Base
belongs_to  :post

and

class Post < ActiveRecord::Base
belongs_to :event

The Post table has a boolean column titled :anon. I want to create a validation when trying to create an event. If the anon field is true then the associated event is valid, otherwise an event is not valid. Is there a way I can do this using Rails associations?


Solution

  • You can use before_create callback here, for this purpose, something like following:

    class Post < ActiveRecord::Base
    belongs_to :event
    before_save :validate_event
    
    def validate_event
      anon ? event.valid : event.invalid  
    end