Rails AJAX表单提交为JSON而不是JS

时间:2013-07-12 02:02:16

标签: ruby-on-rails jquery

以下表格:

<%= form_for @bid, remote:true do |f| %>

    <%= f.label :amount, 'What's your bid??' %>
    <%= f.text_field :amount %>


    <br>
    <%= f.submit "Bid", class: "btn" %>
<% end %>

允许用户点击“出价”按钮提交出价易趣样式。这样做我希望AJAX请求更新我的html以显示如下确认消息:

//create.js.erb
$(".modal-top-messages").html("<%= escape_javascript(render('layouts/messages')) %>")

控制器代码如下所示:

def create
    @bid = current_user.bids.build(params[:bid])

    if @bid.save
      flash.now[:success] = "Bid submitted"
    else
      error_msg = "Error submitting bid. Please try again.\n"  + @bid.errors.collect { |k, v| "#{k}: #{v}" }.join
    end

    if error_msg
      flash.now[:error] = error_msg
    end

    respond_to do |format|
      format.js
      format.html { redirect_to company_path }

    end
  end

现在,当我在视图中点击“出价”按钮时,我在控制台中看到错误:

Started POST "/bids.json" for 127.0.0.1 at 2013-07-11 18:48:59 -0700
Processing by BidsController#create as JSON
Parameters: {"utf8"=>"?", "authenticity_token"=>"F5aQUGgXMYeTZQEpkAs6a501lsrgx
SIr+JxHS8O2Qrw=", "bid"=>{"amount"=>""}}
  ?[1m?[36mUser Load (0.0ms)?[0m  ?[1mSELECT "users".* FROM "users" WHERE "users
"."id" = 3 LIMIT 1?[0m
  ?[1m?[35m (0.0ms)?[0m  begin transaction
  ?[1m?[36m (0.0ms)?[0m  ?[1mrollback transaction?[0m
Completed 406 Not Acceptable in 15ms (ActiveRecord: 0.0ms)

我相信406是由于我的控制器中缺少“respond_to format.json”。我无法弄清楚为什么首先发送JSON响应。

0 个答案:

没有答案