uralika
uralika

Reputation: 203

Active Record Validation Rails 4

I'm trying to validate presence of a zip code upon creation of a book store by checking if the entered zip code corresponds to any zip code in my zip_codes table.

In the book store model, something like:

validates_presence_of :zip_code, unless: ........

The sql statement to find such zip codes is:

select zip_code from book_stores where zip_code not in (select distinct zip_code from zip_codes);

Upvotes: 1

Views: 120

Answers (2)

kempchee
kempchee

Reputation: 470

I would use a before_save hook instead here. The way this works, is it calls a function and only saves the record if the function returns true. So for example:

BookStore.rb:

before_save :check_zip_code

def check_zip_code
  connection = ActiveRecord::Base.connection

  zip_codes=connection.execute('select "zip_code" from "book_stores" where "zip_code" not in (select distinct "zip_code" from "zip_codes")').to_a

  if self.zip_code&&(zip_codes.include?(self.zip_code)
    return true
  else
    return false
  end
end

You can also validate the presence of zip_code to simplify the before_save call, since validations happen before the before_save method is called. You could then assume that self.zip_code is defined.

Upvotes: 0

Chris Gunther
Chris Gunther

Reputation: 339

You'll want to define your own validation method:

validate :zip_code_exists

def zip_code_exists
    errors.add(:zip_code, 'is not valid') unless ZipCode.exists?(zip_code: zip_code)
end

That will add an error message on the zip_code attribute of your model, unless the ZipCode model contains a record who's zip_code matches the zip_code provided.

Upvotes: 2

Related Questions