我正在关注 Railscast #217,它展示了如何从部分构建多步表单。我按照 Ryan 的指示让我的代码工作,但想知道如何转换它以便 Rails 使用 AJAX 加载部分?
users_controller.rb
class UsersController < ApplicationController
...
def new
session[:user_params] ||= {}
@user = User.new
end
def create
session[:user_params].deep_merge!(params[:user]) if params[:user]
params.each do |key,value|
session.deep_merge!(key=>value) if params[:user]
end
@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
用户.rb
class User < ActiveRecord::Base
attr_writer :current_step
def current_step
@current_step || steps.first
end
def steps
%w[step1 step2 step3]
end
def next_step
self.current_step = steps[steps.index(current_step) + 1]
end
def previous_step
self.current_step = steps[steps.index(current_step) - 1]
end
def first_step?
current_step == steps.first
end
def last_step?
current_step == steps.last
end
end
新的.html.erb
<%= simple_form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<%# render @user.current_step, :f => f %>
<div id="form"></div>
<div class="center">
<%= f.submit "Previous", class: "btn btn-primary", :name => "prev_button" unless @user.first_step? %>
<%= f.submit "Next", class: "btn btn-primary", :name => "next_button" unless @user.last_step? %>
<%= f.submit "Submit", class: "btn btn-primary", :name => "submit_button" if @user.last_step? %>
</div>
<% end %>
编辑
我将发布我的部分内容。注意f
变量——我不知道如何使用 AJAX 将它从表单传递到我的部分。
_step1.html.erb
<div class="offset1">
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
</div>
创建.js.erb
$('#form').html('<%= escape_javascript(render(@user.current_step)) %>');
这不起作用,我需要以f
某种方式通过。