Cannon Moyer
Cannon Moyer

Reputation: 3174

How can I check if a field has a validation in Rails 6?

I have a Address model that contains the following validation:

with_options if: Proc.new{|i| i.country && i.country.downcase == "united states"} do
    validates :state, presence: true
end

In my new and edit form, I want to check and see if the state field is required. The following function returns the presence validation but it does not take my conditional into consideration.

Address.new._validators[:first_name]

This code returns

[#<ActiveRecord::Validations::PresenceValidator:0x00007fadebc9d8a8 @attributes=[:first_name], @options={:if=>#<Proc:0x00007fadebc9ebb8@/Users/cannonmoyer/Documents/RailsProjects/treadmilldoctorrails/app/models/address.rb:18>}>]

Is there a way to run the conditional for the validation so that the presence validator doesn't appear on each instance? I am wanting to use this to set required fields within my HTML.

Upvotes: 2

Views: 1040

Answers (1)

spickermann
spickermann

Reputation: 106952

Why don't you just place the condition into a method on its own then you can use the same method in your view to determine if you want to show the states select.

validates :state, presence: true, if: :state_required?

def state_required?
  country && country.downcase == "united states"
end

And in your view you can do something like:

<% if @address.state_required? %>
  # state select
<% end %>

Upvotes: 4

Related Questions