1

我想知道如何在 rails 3 中使用 ajax/jquery 渲染另一个控制器的新动作。

假设我有一个客户和一个销售控制器、模型和视图,我想做的是能够使用 ajax/jquery 从客户索引视图进行新的销售。

为此,我在每个名为“新销售”的客户旁边都有一个按钮,当单击它时,它应该呈现表单以为该客户进行新销售。

我在想的是,它可以通过从销售控制器渲染 new_sale 表单或渲染在客户视图文件夹中创建的新销售表单并在客户控制器内创建一个新操作来创建一个新销售来完成,尽管我不确定如果可以的话。

无论如何,我想知道如何呈现新的销售表格,有什么想法吗?

先感谢您。

编辑** 这是我的代码:

#clients index.html.erb
#I couldnt make work the link like you suggested so i did it like this
<%= link_to "Venta", { :controller => "sales", remote: true, :action => "new", :cliente_id => cliente.id, :class => 'btn btn-small btn-primary', :id => 'btn-venta-clientes-index'} %>

#Div where i want to render the new sale form
<div id="test" class="modal-body"></div>


#new.js.erb inside sales views folder, i tried with the 3 of them one at a time but none work
#$("div#test").html("<%= escape_javascript(j render :partial => "form") %>"); 
#$('div#test').html('<%= escape_javascript(render("form")) %>');
$('div#test').html('<%= j render :partial => "form" %>');


#Sales controller
#I tried removing all formats from the new action but didnt work
def new
  @sale = Sale.new
  @cliente = Cliente.find(params[:cliente_id])

  respond_to do |format|
    #format.html # new.html.erb
    #format.json { render json: @sale }
format.js
  end
end

#I tried removing all formats from the create action but didnt work
def create 
  @sale = Sale.new(params[:sale])

  respond_to do |format|
    if @sale.save
     #format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
     #format.json { render json: @sale, status: :created, location: @sale }
 format.js  { render action: "create" }
    else
     #format.html { render action: "new" }
     #format.json { render json: @sale.errors, status: :unprocessable_entity }
 format.js  { render action: "new" }
    end
  end
end

你知道我在做什么错吗?

4

1 回答 1

2

我用我制定的解决方案大致勾勒了您的情况​​。也许有些事情不是最佳的,有些事情是错误的,但我希望您能比文字更好地理解总体思路:

#clients/index.haml
= render @clients


#clients/_client.haml
.client-container
  %p= client.name 
  ...
  .form-container{ :id => "client-#{client.id}" }
    = link_to "New sale", new_sale_path(:client_id => client.id), :remote => true

#SalesController
def new
  @sale = Sale.new
  @client = Client.find(params[:client_id])
end

#sales/new.js.erb
$("#client-<%= @client.id %>").html("<%= j render :partial => "form" %>");

#sales/_form.haml
#your form code

#SalesController
def create
  @sale = Sale.new(params[:sale])
  if @sale.save
    format.js { render action: "create"}
  else
    format.js { render action: "new" }
  end
end

#sales/create.js.erb
#Here you hide a form and write something like "success".
#You can return "new sale" button (if you decide to remove it.)

此外,ajax 回调在这种情况下非常有用。例如:

$('.your-remote-button').bind 'ajax:success', ->
  $(this).closest('div').fadeOut()
于 2012-05-30T16:25:59.410 回答