form_for远程不刷新页面

时间:2012-11-18 07:27:57

标签: javascript ruby-on-rails

我正在尝试设置我的页面以从主页添加链接。它会更新数据库中的链接,但不会刷新内容。这就是我所拥有的:

控制器/ home_controller.rb

class HomeController < ApplicationController
  def create
    if user_signed_in?
      @new_link = Link.create(:link => params[:email])
      respond_to do |format|
        format.js do
        end
     end
  end
end

视图/家/ index.html.haml

#home
  = render "shares/home_links"

视图/股/ _home_links.html.haml

= simple_form_for Link.new, :remote => true do |f|
  .form-inputs
    = f.input :name, :required => true, :autofocus => true
    = f.input :url, :required => true
    = f.collection_select :category_id, Category.where(:user_id => current_user.id), :id, :name

  .form-actions
    = f.submit 'Save', :class => 'btn btn-info'

视图/家/ create.js.erb

$('#home').replaceWith("<%= escape_javascript(render :partial => 'shares/home_links') %>");

Firebug控制台显示

POST http://localhost:3000/links 302 Moved Temporarily
GET http://localhost:3000/links/45 200 OK (spinner keeps going and browser is slow until I hit refresh)

终端输出是:

Started POST "/links" for 127.0.0.1 at 2012-11-17 23:25:24 -0800
Processing by LinksController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"KPSpEcdrPf1mWMesKT96UY/j1Wozze30LUlno1npT4A=", "link"=>{"name"=>"localhost:3000", "url"=>"http://localhost:3000/", "category_id"=>"5"}, "commit"=>"Save"}
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
   (0.1ms)  BEGIN
  SQL (0.3ms)  INSERT INTO `links` (`category_id`, `created_at`, `name`, `position`, `updated_at`, `url`, `user_id`) VALUES (5, '2012-11-18 07:25:24', 'localhost:3000', NULL, '2012-11-18 07:25:24', 'http://localhost:3000/', 1)
   (0.9ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT
Redirected to http://localhost:3000/links/45
Completed 302 Found in 6ms (ActiveRecord: 1.7ms)


Started GET "/links/45" for 127.0.0.1 at 2012-11-17 23:25:24 -0800
Processing by LinksController#show as JS
  Parameters: {"id"=>"45"}
  Link Load (0.4ms)  SELECT `links`.* FROM `links` WHERE `links`.`id` = 45 LIMIT 1
  Rendered links/show.html.haml within layouts/application (0.9ms)
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  Rendered layouts/_header.html.haml (2.6ms)
  Rendered layouts/_flash.html.haml (0.2ms)
Completed 200 OK in 22ms (Views: 20.5ms | ActiveRecord: 0.7ms)

1 个答案:

答案 0 :(得分:0)

由于行simple_form_for Link.new, ...,内容未被刷新。每次表单呈现时都要实例化一个新的链接对象,而不是检查是否已设置实例变量@new_link。尝试将其更改为:

simple_form_for @new_link || Link.new, ...

编辑:第二个想法,简单地用新的替换当前在浏览器中呈现的表单可能不会更新字段,因为浏览器正在管理表单的内部状态。您必须使用javascript手动设置字段的值。例如,在create.js.erb中:

$('#id-for-name-field').val(@new_link.name)
$('#id-for-url-field').val(@new_link.url)
...