Validation for existence

108 Views Asked by At

I want to validate my entry to existence in database. In other words check if the input data is present in the table, if not let it go, else stop and display error message like in presence validation etc. So as far as i know there is no validates: existence or something like this in Rails 4.2. Question: Is there an easy way to do that?

If not, i can manually check for existence in my controller like that:

@client = Client.where("name = ?", @request.name).take
if @client.present?
  @request.client_id = @client.id
else    
  # some error message
  render 'new'
end

I think this should work, but how to display error message, not flash.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use uniqueness helper to validate that client name is unique or not

class Client < ActiveRecord::Base
  validates :name, uniqueness: true
end

And if that doesn't fulfill your needs then you can always create a custom validation method and add errors

  class Client < ActiveRecord::Base
  validate :some_custom_method

  def some_custom_method
    # check for some condition
    # add error messages if that condition fails
  end
end

P.S if you are using uniqueness helper then make sure to add unique constaint on your db.

update:

You can add error messages like this:

def some_custom_method
  errors.add(:base, "error message") unless some_condition
end

For details checkout working with errors.