I would like to know how to render the new action of another controller with ajax/jquery in rails 3.
Lets say i have a Clients and a Sales controller, model and view, what i would like to do is to be able to make a new sale from the clients index view using ajax/jquery.
For this i have a button next to each client named “New Sale”, when its clicked it should render the form to make a new sale for that client.
What i was thinking is that it could be done either rendering the new_sale form from the Sales controller or rendering a new sale form created inside the Clients views folder and create a new action inside the Clients controller to create a new sale, though im not sure if that could be done.
Anyway i would like to know how to approach to render that new sale form, any thoughts?
Thank you in advance.
EDIT **
Here is my code:
#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
Do you know what am i doing wrong?
I sketched roughly your situation with a solution that I made. Maybe something is not optimal, something is wrong, but I hope you will understand the general idea better than by words:
Also, ajax callbacks are very useful in this situation. For example: