Rails验证jquery hide / show上的字段

时间:2014-08-20 13:50:18

标签: ruby-on-rails ruby ruby-on-rails-3

如果项目有menu_type = 'Lunch',我有一个复选框来显示收货地址,表格的这一部分用jQuery隐藏,直到复选框被选中,但如果选中复选框,如何验证这些字段?< / p>

视图

<%= simple_form_for @order do |f| %>
        <div class="row">
            <div class="large-4 columns">
                <h4>Customer Details</h4>
                <%= f.input :first_name %>
                <%= f.input :last_name %>
                <%= f.input :email %>
                <%= f.input :phone_number %>
            </div>
            <div class="large-4 columns">
                <h4>Billing Address</h4>
                <%= f.input :billing_line_1, :label => 'Billing Address Line 1' %>
                <%= f.input :billing_line_2, :label => 'Billing Address Line 2' %>
                <%= f.input :billing_line_3, :label => 'Billing Address Line 3' %>
                <%= f.input :billing_postcode, :label => 'Billing Postcode' %>
                <% if @order.order_items.first.item.menu_type == 'Lunch' %>
                <%= f.input :lunch_delivery, :label => 'Lunch Time Delivery?' %>
                <% end %>
                <div id="deliveryAddress">
                    <h4>Delivery Address</h4>
                    <%= f.input :delivery_line_1, :label => 'Delivery Address Line 1' %>
                    <%= f.input :delivery_line_2, :label => 'Delivery Address Line 2' %>
                    <%= f.input :delivery_line_3, :label => 'Delivery Address Line 3' %>
                    <%= f.input :delivery_postcode, :label => 'Delivery Postcode' %>
                </div>
            </div>
            <div class="large-4 columns">
                <%= f.button :submit, "Place order" %>
            </div>
        </div>
        <% end %>

模型

class Order < ActiveRecord::Base
  attr_accessible :billing_line_1, :billing_line_2, :billing_line_3, :billing_postcode, :delivery_line_1, :delivery_line_2, :delivery_line_3, :delivery_postcode, :phone_number, :email, :first_name, :last_name, :lunch_delivery

  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :email, presence: true
  validates :billing_line_1, presence: true
  validates :billing_postcode, presence: true
  validates :phone_number, presence: true
end

JS

$("#order_lunch_delivery").click ->
  if $(this).is(":checked")
    $("#deliveryAddress").show()
  else
    $("#deliveryAddress").hide()
  return

1 个答案:

答案 0 :(得分:1)

听起来你正在寻找conditional validation。它看起来像

 validates :delivery_line_1, presence: true, if: :lunch_delivery