Search code examples
ruby-on-railsmodelactioncontroller

how to validate a record in table before saving in ruby on rails


I am new to Ruby on Rails I have a scenario in which I have a form which has some fields. One of the field values I need to validate against a table which has the data . I want to restrict the user from saving any data unless the field is validated with the table records.

Initially I added the code in controller to validate that but I have other fields which I need to validate as empty so it did not work .

Also I want the the validation error to be part of other errors.

I tried the below code in the model file

before_create :validate_company_id

def validate_company_id
    cp = Company.find_by_company_id(self.company)
    if @cp != nil
       return
     else
        self.status ||= "Invalid"    
     end
end

But its not validating , could you help me how I can validate it .

regards Surjan


Solution

  • instead of using before_create. You can tell the model to use a custom method for validation as follows

    validate :validate_company_id
    
    def validate_company_id
        cp = Company.find_by_company_id(self.company)
        if cp.nil?
          errors.add(:company, 'Invalid Company ID')
        end
    end