I want to load a partial using AJAX in my create action. From tutorials I know the way to do this is to include the line format.js alone by itself in the respond_to block and create a create.js.erb file. But I have code in my create action which I need executed. If I put all of this code within a format.js {} block the partial doesn’t get loaded. I guess I’m not sure what should be included inside this block?
This sort of works:
def create
respond_to do |format|
format.html do
session[:user_params].deep_merge!(params[:user]) if params[:user]
@user = User.new(session[:user_params])
@user.current_step = session[:user_step]
if params[:prev_button]
@user.previous_step
elsif @user.last_step?
@user.save
else
@user.next_step
end
session[:user_step] = @user.current_step
if @user.new_record?
render :new
else
session[:user_step] = session[:user_params] = nil
flash[:success] = "Welcome to Friends First!"
redirect_to @user
end
end
format.js
end
end
My new.html.erb looks like this:
<%= form_for(@user, :html => { :class => "form-horizontal" }, remote: true) do |f| %>
<%= render 'shared/error_messages' %>
<div id="partial">
<%= render "#{@user.current_step}", :f => f %>
</div>
<div class="control-group">
<div class="controls">
<%= f.submit "Previous", class: "btn btn-primary", :name => "prev_button" unless @user.first_step? %>
<%= f.submit "Next", class: "btn btn-primary" %>
</div>
</div>
But for some reason @user.first_step? is not working once I load a partial.
create.js.erb
$("#partial").html("<%= escape_javascript(render('step2')) %>");
What I really want is this: render(@user.current_step)
You can do all your logic and then handle proper format. Furthermore you can use more than one format for your views.
There is and example from Diaspora source code:
You shouldn’t do any redirects if something fail because user stay at page anyway. But you might want use client-side validation.
So you might use
format.jsfor your success case and reload part of your HTML using partial. For example: