Tintin81
Tintin81

Reputation: 10207

How to check if value is included in hash in ActiveRecord validations?

I have a Project model and I need to test if the billing_address_type is valid.

class Project < ActiveRecord::Base

  validates :billing_address_type, :inclusion  => { :in => %w(h o) }

  def billing_address_types
    options = {"Home" => "h", "Organisation" => "o"}       
    if person.present?
      options.delete("Home") if person.address.blank?
      options.delete("Organisation") if person.organisation.blank?
    end
    options
  end

The validates line is wrong, however. I need to check for inclusion of the hash values returned by the method billing_address_types.

How can I check for the hash values only?

Thanks for any help...

Upvotes: 3

Views: 2795

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

You can pass lambda or a new Proc to the :in option which will be dynamically evaluated, and use the values method on the hash returned from billing_address_types to get the hash values only:

validates :billing_address_type, :inclusion  => { :in => lambda { |a| a.class.billing_address_types.values } }

See the documentation for details.

Upvotes: 3

Related Questions