Search code examples
ruby-on-railsforeign-keysscaffolding

Validate existence of asssociation Rails


I am new to rails, well, and I'm kind of confused. I have three tables

 ______________        ____________________        _____________________
|   employees  |      |   abilitys         |      |   services          |
|--------------|      |--------------------|      |---------------------|
|id   | integer|__    |id         | integer|    __|id          | integer|
|name | string |  |_->|employee_id| integer|   |  |description | string |
|______________|      |service_id | integer| <-|  |_____________________|
|______________|      |____________________|

I want to know If I can accept the insertion of an ability only in case the employee does exist in the employees table. The same goes for the service_id.

Do I have to validate that in the hability.rb file or do the validation at the view ?

thank you.


Solution

  • Yes, you can do this in the Model (the validations should be defined in the Model):

    class Ability < ActiveRecord::Base
      belongs_to :employee
      belongs_to :service
    
      validates :employee, :presence => true, :associated => true
      validates :service, :presence => true, :associated => true
    end