使用Rails和AJAX提交表单和更新页面

时间:2015-06-27 16:16:18

标签: ajax ruby-on-rails-4

在索引页面上,我有一个表单来创建一个新对象。在提交表单时,我想用新对象更新页面而不刷新页面。表单提交并创建对象但页面未更新。表单被隐藏,这是所需的效果,但新对象不显示。日志将堆栈跟踪显示为

Started POST "/products" for ::1 at 2015-06-27 18:38:14 +0100
Processing by ProductsController#create as JS
Parameters: {"utf8"=>"✓", "product"=>{"name"=>"Pets"}, "button"=>""}
User Load (1.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
(0.2ms)  BEGIN
SQL (0.4ms)  INSERT INTO products" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["name", "Pets"], ["created_at", "2015-06-27 17:38:14.418558"], ["updated_at", "2015-06-27 17:38:14.418558"]]  
(6.1ms)  COMMIT
(0.4ms)  SELECT COUNT(*) FROM "items" WHERE "items"."product_id" = $1    [["product_id", 83]]
Rendered products/_product.haml (1.4ms)
Rendered products/create.js.erb within layouts/admin (2.7ms)
Rendered products/index.haml within layouts/admin (12.8ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.haml (0.6ms)
Rendered layouts/_footer.haml (0.1ms)
Completed 200 OK in 139ms (Views: 134.7ms | ActiveRecord: 2.1ms)

表单在index.haml

%div{class: "col-md-4 col-md-offset-2 product-list"}
  - @products.each do |product|
    = render 'product', product: product

%div{class: "col-md-4"}
  .btn.btn-success.btn-sm.add-product
  Add a product

.add-product-form
  = form_for @product, remote: true, html: {class: "product disabled"} do |f|

  .product-add
    .form-group
      = f.label :name 
      = f.text_field :name, class: "form-control"
    .form-group
      .controls
        = f.button '+ Add', class: 'btn btn-success save-product'
        .btn.btn-warning.product-cancel
          Cancel

products.js.coffee

$ ->
  $(document).on "click", ".save-product", ->
    $('.add-product-form').hide()

products_controller.rb

def create
  @product = Product.new(product_params)
  if @product.save
    respond_to do |format|
      format.html
      format.js
    end
  end
end

create.js.erb

$(".product-list").append("<%= j render 'product', product: @product} %>");

_product.haml

%h4
  = link_to product_url(product.id) do
    = product.name.capitalize

我对js / coffeescript很新。如何使用我看到的新项目来更新视图?

1 个答案:

答案 0 :(得分:1)

你在js中的渲染线是错误的,要么写

render 'product', product: @product

或写

render partial: 'product', locals: { product: @product }