Create.js.erb没有在带有Rails的AJAX中显示

时间:2013-01-01 03:06:02

标签: ruby-on-rails ajax jquery

我正在尝试让我的rails应用程序中的表单上的AJAX工作,大约75%的方式。我有一个表格,一个人可以创建一个活动,并用技能标记该活动。我想为他们提供在表单中创建新技能的能力。我可以用表单替换“创建新技能”链接,然后保存记录没有任何问题。我的问题是保存记录后,rails会将我重定向回我的主页,而不是回到带有表单的页面。如果用户通过典型的HTML表单创建技能,则重定向是正常行为。

我页面上的链接,用于创建一种新技能,转换为一种形式:

<%= link_to "Create A New Skill", new_skill_path, :id => "new-skill-link", remote: true %>

替换链接的新技能表单:

<%= form_for Skill.new, :remote => true do |f| %>
  <%= f.text_field :description %>
  <%= f.submit "Save", :class => 'btn-large btn-primary' %>
<% end %>

我的技能控制器(New和Create方法):

def new
  @skill = Skill.new
  @tags = current_user.tags

  respond_to do |format|
    format.html
    format.js
  end
end

def create
  @skill = current_user.skills.new(params[:skill])
  params[:skill][:tag_ids] ||= []

  respond_to do |format|
    if @skill.save
      flash[:success] = "Skill was successfully created!"
      format.html { redirect_to home_page_url }
      format.js { render action: "create" }
    else 
      flash.now[:error] = "There was an error saving your skill."
      format.html { render action: "new" }
      format.js { render action: "new" }
    end
  end
end

我的new.js.erb:

$("#new-skill-link").hide().after('<%= j render("skills/remote_form") %>');

我的create.js.erb:

$("#new-skill").remove();
$("#new-skill-link").show();
$(".skill-list ul").append('<%= j render(@skill) %>');

似乎rails将请求解释为HTML,因此它正在响应HTML页面。我尝试将:format => :js添加到技能表单中,但rails只是在我的浏览器中呈现了javascript而没有解释它。

当我查看Web服务器上的日志时,我没有看到任何错误。我明白了:

Started POST "/skills" for 127.0.0.1 at 2012-12-31 20:02:16 -0700
Processing by SkillsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxxxx", "skill"=>{"description"=>"Example Skill"}, "commit"=>"Save"}
  User Load (62.8ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'xxxxx' LIMIT 1
  (0.1ms)  begin transaction
  SQL (15.4ms)  INSERT INTO "skills" ("created_at", "description", "updated_at", "user_id") VALUES (?, ?, ?, ?)  [["created_at", Tue, 01 Jan 2013 03:02:16 UTC +00:00], ["description", "Example Skill"], ["updated_at", Tue, 01 Jan 2013 03:02:16 UTC +00:00], ["user_id", 1]]
  (1.4ms)  commit transaction
Redirected to http://localhost:3000/home_page
Completed 302 Found in 96ms (ActiveRecord: 79.7ms)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

原因是,你不应该在create方法中进行重定向,因为AJAX请求在中间有点丢失(你可以通过Firebug / FF看到它)。

以下是示例代码:

Ex:假设我有一个叫做项目的脚手架

projects_controller.rb

class ProjectsController < ApplicationController
  @project = Project.new(params[:project])
  if @project.save
      flash.now[:success] = ["#{@project.name} sucessfully created"]
  else
      flash.now[:errors] = @project.errors.full_messages 
  end
end

在view / projects

_form.html.erb

<div id="message"></div>
<%= form_for @project :remote => true, :html => { :class => 'form-horizontal' } do |f| %>
  <%= f.text_field :name, :class => 'span3', :placeholder => "Project name" %> 
  <%= f.submit nil, :class => 'btn btn-success' %>
<% end %>

create.js.erb

$("#message").html("<%= escape_javascript raw(flash_display) %>");

in helper

module ApplicationHelper
  def flash_display
    response = "<div class='alert #{alert_class}'>"
    response += "<button type='button' class='close' data-dismiss='alert'>x</button>"
    flash.each do |name, msg|
      msg.each do |m|
        response = response + content_tag(:p, m)  
      end
    end
    response += "</div>"
    flash.discard
    response
  end

  private
  def alert_class
    css_class = case flash.first[0]
      when :errors then "alert-error"
      when :success then "alert-success" 
      when :notifications then "alert-block"   
    end
    css_class  
  end
end

所以你可以看到,我没有从我的create方法重定向,保存之后我只是传递了状态的消息。因此,您的页面不会刷新,只会更新消息。