使用AJAX多步形式的Rails形式、AJAX、Rails

2023-09-10 18:12:50 作者:花醉伊人泪

我下面Railscast#217,显示如何建立一个多形式表现出来谐音的。我跟瑞安的方向,并得到了我的code的工作,但不知道如何转换这种让Rails会使用AJAX来加载谐音?

I'm following Railscast #217 which shows how to build a multistep form out of partials. I followed Ryan's directions and got my code to work but was wondering how to convert this so that Rails will use AJAX to load the partials?

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

user.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

new.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的形式

EDIT I'm going to post one of my partials. Notice the f variable - I don't know how to pass that into my partial from the form using 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>

create.js.erb

$('#form').html('<%= escape_javascript(render(@user.current_step)) %>');

这是不行的,我需要通过 F 在不知。

This doesn't work, I need to pass f in somehow.

推荐答案

一个非常简单的方法,使之感觉更ajaxy,是使用的 pjax护栏的。

A really simple way to make it feel more ajaxy, is to use the pjax-rails.

您需要改变几乎微乎其微,只定义了 pjax容器 DIV将被重新加载。希望这可以帮助。

You will need to change almost next to nothing, only define the pjax-container div that will be reloaded. Hope this helps.