使用复选框使用AJAX填充rails表单

时间:2017-01-19 02:18:46

标签: jquery ruby-on-rails json ajax

我很难集成AJAX调用来填充表单。我不知道我是否正确格式化了这个以及我应该使用什么来填写表单上的jSON数据。任何帮助深表感谢。

最终目标是能够单击复选框以在表单中填充新联系人的地址。我希望能够使用与其所属客户相同的地址填充地址。

我查看了一些示例,其中AJAX用于填充运输表单地址与结算表单地址相同但是这对我不起作用,因为我在页面上没有这两种地址表单。

这是新联系人的观看页面的一部分:

  <div class='row'>
    <div class='col-sm-6 col-sm-offset-2'>
      <p>Address Same as Customer <input id="same_customer_address" name="accept" type="checkbox" value="1" /></p>
    </div>
  </div>

  <%= f.fields_for :address do |address| %>

    <div class="form-group">
      <%= address.label :line1, class: "col-sm-2 control-label" %>
      <div class="col-sm-6">
        <%= address.text_field :line1,class: "form-control", id: 'line1'%>
      </div>
    </div>

    <div class="form-group">
      <%= address.label :line2, class: "col-sm-2 control-label" %>
      <div class="col-sm-6">
        <%= address.text_field :line2,class: "form-control", id: 'line2'%>
      </div>
    </div>

    <div class="form-group">
      <%= address.label :city, class: "col-sm-2 control-label" %>
      <div class="col-sm-6">
        <%= address.text_field :city,class: "form-control", id: 'city' %>
      </div>
    </div>

    <div class="form-group">
      <%= address.label :state, class: "col-sm-2 control-label" %>
      <div class="col-sm-6">
        <%= address.text_field :state,class: "form-control", id: 'state' %>
      </div>
    </div>

    <div class="form-group">
      <%= address.label :zip, class: "col-sm-2 control-label", id: 'zip' %>
      <div class="col-sm-6">
        <%= address.text_field :zip,class: "form-control" %>
      </div>
    </div>

  <% end %>
Customer
has_many :contacts
belongs_to :address

Contact
belongs_to :address
belongs_to :customer
Contacts Controller
  def new
    authorize Contact
    @contact = @customer.contacts.new
    @contact.build_address
    phone_types = ['Cell','Work','Home']
    3.times { @contact.phones.build(phone_type: phone_types.shift) }
    @contact_types = @@contact_types
    # authorize @customer
  end

  def same_as_customer
    @customer = Customer.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render json: @customer }
    end
  end
  private
  # Use callbacks to share common setup or constraints between actions.
  def set_customer
    @customer = Customer.find(params[:id])
  end

  def set_contact
    @contact = Contact.find(params[:contact_id])
  end
  # Never trust parameters from the scary internet, only allow the white list through.
  def contact_params
    params.require(:contact).permit(:first_name, :last_name, :email, :email_sec, :title, :contact_type,
     address_attributes: [ :line1, :line2, :city, :state, :zip, :id ],
     phones_attributes: [ :phone_type, :number, :id ])
  end
end
$('#same_customer_address').click(function() {
var customer_address;
$.ajax({
  type: 'GET',
  url: "/contacts/same_as_customer",
  datatype: "json",
  data: { line1: line1,
          line2: line2,
          city: city,
          state: state,
          zip: zip },
  success: function(data){
    customer_address = data;
  }
});
if ($("#same_customer_address").is(':checked')) {
  console.log("customer address is filled");
  $('#line1').val("customer_address.line1").val();
  $('#line2').val("customer_address.line2").val();
  $('#city').val("customer_address.city").val();
  $('#state').val("customer_address.state").val();
  $('#zip').val("customer_address.zip").val();
  } else{
    console.log("field is empty");
    $('#line1').val("");
    $('#line2').val("");
    $('#city').val("");
    $('#state').val("");
    $('#zip').val("");
  };
});

3 个答案:

答案 0 :(得分:0)

检查这是否有效......

 $('#same_customer_address').change(function() {
  if(this.checked) {
    var customer_address;
    $.ajax({
      type: 'GET',
      url: "/contacts/same_as_customer",
      datatype: "json",
      success: function(data){
        customer_address = data;
        console.log("customer address is filled");
        $('#line1').val("customer_address.line1");
        $('#line2').val("customer_address.line2");
        $('#city').val("customer_address.city");
        $('#state').val("customer_address.state");
        $('#zip').val("customer_address.zip");
      }
    });
  } else {
    console.log("field is empty");
    $('#line1').val("");
    $('#line2').val("");
    $('#city').val("");
    $('#state').val("");
    $('#zip').val("");
  };
});

# Contact Controller

  def same_as_customer
    @customer = Customer.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render json: @customer.address }
    end
  end

替代方法

我可能会建议一种替代方法...不要填充表单,而是将该复选框的参数传递为true并复制控制器中的地址,然后保存记录。

答案 1 :(得分:0)

使用类而不是ID:

<div class='row'>
    <div class='col-sm-6 col-sm-offset-2'>
        <p>Address Same as Customer <input id="same_customer_address" name="accept" type="checkbox" value="1" /></p>
    </div>
</div>

<%= f.fields_for :address do |address| %>
    <div class="address-fields">
        <div class="form-group">
            <%= address.label :line1, class: "col-sm-2 control-label" %>
            <div class="col-sm-6">
                <%= address.text_field :line1, class: "form-control line1" %>
            </div>
        </div>

        <div class="form-group">
            <%= address.label :line2, class: "col-sm-2 control-label" %>
            <div class="col-sm-6">
                <%= address.text_field :line2, class: "form-control line2"%>
            </div>
        </div>

        <div class="form-group">
            <%= address.label :city, class: "col-sm-2 control-label" %>
            <div class="col-sm-6">
                <%= address.text_field :city, class: "form-control city" %>
            </div>
        </div>

        <div class="form-group">
            <%= address.label :state, class: "col-sm-2 control-label" %>
            <div class="col-sm-6">
                <%= address.text_field :state, class: "form-control state" %>
            </div>
        </div>

        <div class="form-group">
            <%= address.label :zip, class: "col-sm-2 control-label"%>
            <div class="col-sm-6">
                <%= address.text_field :zip, class: "form-control zip" %>
            </div>
        </div>
    </div>
<% end %>

现在让我们使用类将JSON值复制到输入:

var $form = $('#my_form_id');

$form.on('copy_address', function(){
  $.getJSON("/contacts/same_as_customer").done(function(data){
    var attributes = ['line1', 'line2', 'city', 'state', 'zip'];
    $.each(attributes, function(i, attr){
      $fields.find('.form-control .' + attr).val(data[attr]);
    });
  });
});

$form.find('#same_customer_address').one('change', function(){
   if (this.checked) {
     $form.trigger('copy_address');
   }
});

答案 2 :(得分:0)

所以我最终在后端填充了记录。它没有像我最初想要的那样填充表单,但是它做了我需要它做的更新地址记录。

联络管理员:

def create
    puts params.inspect
    authorize Contact

    @contact = @customer.contacts.new(contact_params)

    same_as_customer

    @contact.update({user_id: current_user.id}.tap do |h|
                h[:address] =  @address if @address
            end
        )

    if @contact.save
        params[:contact][:emails].each do |email|
        @contact.emails.create(email:email)
      end

        redirect_to customer_account_url(@customer), notice: 'Contact created!'
    else
        @contact_types = @@contact_types
        @contact.errors.full_messages
        render :new
        # render json: @contact.errors, status: :unprocessable_entity
    end
  end

  def same_as_customer
    if params[:customers][:address] == '1'
         puts "checkbox is checked"
        @address = Address.create!(@customer.address.as_json.except('id'))
    else
         puts "checkbox is unchecked"
    end
  end

新联系人视图:

<div class='row'>
    <div class='col-sm-6 col-sm-offset-2'>
      <p>Address Same as Customer <input id="same_customer_address" name="customers[address]" type="checkbox" value="1" /></p>
    </div>
</div>