How can I perform a validation only if the value of a hidden_field matches a specified value?
For example, I have two forms each with a separate submit button and a separate hidden_field, the value of which determines whether to run one set of validations or another.
The problem seems to be with the hidden_field check (if I replace it with just a true/false value the rest of the code works).
Model:
validates :new_email, presence: true, length: { minimum: 1 }, on: :update, if: :email_update?
validates :new_password, presence: true, confirmation: true, length: { minimum: 1 }, on: :update, if: :password_update?
validates :new_password_confirmation, presence: true, on: :update, if: :password_update?
validate :password_retype, on: :update
# before_save :copy_values
attr_accessor :remember_token,
:new_email,
:new_password,
:existing_password,
:update_type
def email_update?
update_type == "email_only"
end
def password_update?
update_type == "password_only"
end
View:
<h1>メールアドレス変更</h1>
<%= form_for(@customer) do |f| %>
<p>
<%= f.label :new_email, "Email" %><br>
<%= f.email_field :new_email, placeholder: "Email" %>
</p>
<p>
<%= f.label :existing_password, "パスワード" %><br>
<%= f.password_field :existing_password, placeholder: "Password" %>
</p>
<p>
<%= f.submit "変更する" %>
<%= hidden_field :update_type, "email_only" %>
</p>
<% end %>
<h1>パスワード変更</h1>
<%= form_for(@customer) do |f| %>
<p>
<%= f.label :existing_password, "現在のパスワード" %><br>
<%= f.password_field :existing_password, placeholder: "Old Password" %>
</p>
<p>
<%= f.label :new_password, "新しいパスワード" %><br>
<%= f.password_field :new_password, placeholder: "New Password" %>
</p>
<p>
<%= f.label :new_password_confirmation, "新しいパスワード(確認用)" %><br>
<%= f.password_field :new_password_confirmation, placeholder: "Confirm New Password" %>
</p>
<p>
<%= f.submit "変更する" %>
<%= hidden_field :update_type, "password_only" %>
</p>
<% end %>
Controller:
def edit
@error_messages = []
@customer = Customer.find_by(params[:customerID])
end
def update
@error_messages = []
@customer = Customer.find_by(params[:customerID])
if @customer.update(customer_params)
#if @customer.update_attributes(customer_params)
render "edit"
else
render "edit"
end
end
private
def customer_params
params.require(:customer).permit( :new_email,
:new_password,
:new_password_confirmation,
:existing_password,
:update_type )
end
Params:
--- !ruby/hash:ActionController::Parameters
utf8: "✓"
_method: patch
authenticity_token: zlYVtgQ0LuhYEpM3cRNf9QwhH8+0THluUTEGxEYprybcJrilWKHiUkJ5ypo1JnKRsbtsDTUp+o1xuRr/Pbkp2w==
customer: !ruby/hash:ActionController::Parameters
new_email: ''
existing_password: ''
commit: "変更する"
update_type: !ruby/hash:ActionController::Parameters
email_only: ''
controller: customers
action: update
id: '2'
This has been stumping me for the best part of two days now. :(
You should do