私のrails3アプリケーションでは、ユーザーは[アイテムの追加]リンクをクリックしてリストにアイテムを追加できます。このリンクをクリックすると、AJAXが呼び出されてnew_itemフォームが取得されます。私が働いているその部分。問題は、new_itemフォームを送信すると、:remote => trueを指定しても、「リモート」フォームとして認識されないように見えることです。new_itemフォームがサーバーから返され、ページに挿入された後、UJSなどを再初期化する必要があることは明らかですが、方法がわかりません。
これが私のコードです:
_new.html.haml(新しいアイテムフォーム)
= form_for [@list, @item], :remote => true, :html => {:class => 'form-inline'} do |f|
.input-append
= f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
%button#picture.btn
%span.icon-camera
%button#link.btn{:style => "font-size: 10px;"}
http://
#link-field.field.margin.hidden-field-margin
= f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
#picture-field.field.margin.hidden-field-margin
= f.file_field "picture"
= f.hidden_field "picture_cache"
.clearfix
= f.submit "Add Item", :class => 'btn', :id => "add-item"
lists.js.coffee
# this retrieves the new item form and places it in-line in the page
$("#new_list")
.bind "ajax:success", (evt, xhr, settings) ->
$("#list-item").html(xhr)
# when the new item form (returned from the server) is submitted here, it doesn't appear to be submitted via AJAX
$("#new_item #add-item")
.live "ajax:success", (evt, xhr, settings) ->
alert "this request worked"
items_controller.rb
class ItemsController < ApplicationController
respond_to :html, :xml, :json
def create
@list = List.find(params[:list_id])
@item = @list.items.create!(params[:item])
if @item.save
respond_with do |f|
f.html do
if request.xhr?
f.json { render :json => {:result => "ok"}}
else
redirect_to @list, :notice => "Item was successfully created."
end
end
end
end
end
end
new_itemフォームを送信すると、JSコンソールに次のようなエラーが表示されます...空白のcreate.js.erbテンプレートがありますが、これを探しておらず、リクエストをajaxとして認識していません。リクエスト。より良い単語がないために、サーバーから返されたフォームを「ujs」で再度有効にするにはどうすればよいですか?
Template is missing
Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in: * "/Users/aressidi/Projects/intralist/app/views" * "/Users/aressidi/.rvm/gems/ruby-1.9.3-p194/gems/devise-2.1.2/app/views"
編集-アラートをトリガーできるようにする更新されたコントローラーコードは次のとおりです。
class ItemsController < ApplicationController
respond_to :html, :xml, :json
def create
@list = List.find(params[:list_id])
@item = @list.items.create!(params[:item])
if @item.save
respond_with do |f|
f.html do
if request.xhr?
render :json => {:result => "ok"}
else
redirect_to @list
end
end
end
end
end
end