2017-01-22 45 views
2

在添加參考書目表單中,我創建了一個添加作者表單,該表單添加了使用json的作者。respond_to format.html參數太少

這工作正常。

但是,當作者被添加到數據庫時,我想顯示一條成功消息。

這是我的代碼:

def create 
    @auteur = Auteur.new(params_auteur) 
    respond_to do |q| 
     if @auteur.save 
      format.html{ redirect_to @auteur, notice: 'Auteur added successfully.'} 
      format.js{} 
      format.json{ 
       render json: @auteur, status: :created, location: @auteur 
      } 
     else 
      format.html{ render action: "new"} 
      format.json{ render json: @auteur.errors, status: :unprocessable_entity} 
     end 
    end 
end 

然後,我添加包含此代碼的文件views/auteurs/create.js.erb

$("<%= escape_javascript(render @auteur) %>").appendTo(".bloque_ajoute_auteur"); 

錯誤消息我得到的的(成功)插入後立即產生新作者加入數據庫:

Completed 500 Internal Server Error in 10ms (ActiveRecord: 1.6ms) 
ArgumentError (too few arguments): 
app/controllers/administration/auteurs_controller.rb:23:in `format' 
app/controllers/administration/auteurs_controller.rb:23:in `block in create' 
app/controllers/administration/auteurs_controller.rb:21:in `create' 

第21行是o f respond_to塊;第23行是format.html{ redirect_to @auteur, notice: 'Auteur ajouté.'}

我以爲我已經很密切關注這一點:http://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns

回答

0

你的代碼最終調用內核的format instance method,而不是使用傳遞給respond_to塊的參數,這是應該發生的。

此方法需要更多的參數,顯然在這種情況下不會提供。

要解決此問題,請將參數名稱從q更改爲format

3

應該respond_to do |format|。只要它在沒有聲明的情況下到達format的第一個實例,它就會失敗。

+0

這是正確的!我的愚蠢的錯誤。但是,根本沒有任何消息被這個函數發回(在服務器日誌和firefox開發工具中都沒有)。 – thiebo