如果hidden_field的值与指定值匹配,我该如何执行验证?
例如,我有两个表单,每个表单都有一个单独的提交按钮和一个单独的hidden_field,其值决定是运行一组验证还是另一组验证。
问题似乎是使用hidden_field检查(如果我只用其他代码的真/假值替换它)。
型号:
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
查看:
<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 %>
控制器:
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'
这一直是我两天中最好的一部分。 :(
答案 0 :(得分:0)
你应该做
<%= f.hidden_field :update_type, :value => "email_only or password_only" %>