我想知道如何在rails 3中使用ajax / jquery渲染另一个控制器的新动作。
假设我有一个客户端和销售控制器,模型和视图,我想要做的是能够使用ajax / jquery从客户端索引视图中进行新的销售。
为此我在每个名为" New Sale"的客户旁边都有一个按钮,当点击它时,它应该呈现该表格以便为该客户进行新的销售。
我的想法是,可以从Sales控制器渲染new_sale表单或在Clients视图文件夹中创建新的销售表单,并在Clients控制器内创建新的操作以创建新的销售,尽管我不确定是否可以这样做。
无论如何,我想知道如何处理新的销售形式,任何想法?
提前谢谢。
编辑** 这是我的代码:
#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
你知道我做错了什么吗?
答案 0 :(得分: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()