实现ajax请求以创建/编辑rails对象

时间:2012-12-22 19:42:49

标签: ruby-on-rails ajax

我正在尝试在我的修改用户页面中创建添加/修改信用卡表单。为此,我尝试在客户控制器中实现对编辑和创建函数的ajax调用。

这是模态窗口中更新按钮的代码:

<%= button_tag "Update", :class =>"btn submit-button", :type => 'button', :onclick => "onUpdateCard('#{current_user.id}');"%>

这是它调用的函数:

function onUpdateCard(id) {
this.id = id;

// disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled");
var card_number = document.getElementById('card_number').value;
var card_code = document.getElementById('card_code').value;
var card_month = document.getElementById('card_month').value;
var card_year = document.getElementById('card_year').value;

var response = Stripe.createToken({
    number: $('#card_number').val(),
    cvc: $('#card_code').val(),
    exp_month: $('#card_month').val(),
    exp_year: $('#card_year').val()
}, stripeResponseHandler);        
// allow the form to submit with the default action
return false;
};

function stripeResponseHandler(status, response) {
if (response.error) {
    $(".payment-errors").text(response.error.message);
    $(".submit-button").removeAttr("disabled");
} else {
    var token = response['id'];
    var new_url = "/users/" + this.id + "/customers/new";
    var edit_url = "/users/" + this.id + "/customers/1/edit";
    $.ajax({
        type:'GET',
        url:  edit_url,
        data: {'stripe_card_token': token}
    });
}
return false;
};

在控制器中有编辑功能:

def edit
    @user = current_user
    @customer = @user.customer    
    stripe_customer = Stripe::Customer.retrieve(@customer.stripe_customer_token)
    stripe_customer.card = params[:stripe_card_token]
    stripe_customer.save
end

你能帮我弄清楚如何正确处理ajax吗?我不确定如何正确调试......

1 个答案:

答案 0 :(得分:3)

这里我建议使用AJAX处理更新请求的替代方案。

我没有改进或纠正你的代码,而是给你一种在Rails 3中处理AJAX请求的方法。

一个。查看

无论您想使用AJAX调用在数据库中更新哪些信息,您都将通过表单。因此,要发出AJAX请求,您需要添加:remote =&gt;你的形式是真的。 Rails提供了这个帮助器。

<%= form_for @customer, :url => admin_customers_path, :method => :post, :remote => true, :html => { :id => "customer-form" } do |form|-%>
      <%= render :partial => 'admin/customers/form', :object => form %>
      <%= form.submit 'Update' %>
<% end %>

在_form.html.erb中,您可以在编辑表单中添加任何想要添加的文本字段或其他内容

湾控制器

由于“:remote =&gt; true”,表单提交将在保存客户数据后的更新操作中发出JS请求 控制将用于format.js然后它将在视图中查找update.js.erb。

def update
  if @customer.update_attributes(params[:customer])
    respond_to do |format|
      format.html {
                  flash[:success] = "customer's info was updated Successfully."
                  redirect_to customers_path
      }
      format.js
    end
  else
    respond_to do |format|
      format.html {
                  flash[:error] = @customer.errors.present? ? @customer.errors.full_messages.join('<br />') : "Oops! There is some problem with category update."
                  render :edit
      }
      format.js
    end
  end
end

℃。 update.js.erb

成功更新后你可以做些什么。假设您想要突出显示某个div,那么您可以这样做。

  $('.target-div').effect("highlight", {}, 2500);