我想在我的AJAX實現類型的應用程序,但我的創建操作得到一個缺失的模板錯誤(Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}.
)。不應該有一個create.html.erb
頁面,因爲items
創作發生在一個lists#show
頁:實現AJAX創建,缺少模板(創建)錯誤
<div class='new-item'>
<%= render 'items/form' %>
</div>
<div class="js-items">
<% @items.each do |item| %>
<%= div_for(item) do %>
<p><%= link_to "", list_item_path(@list, item), method: :delete, remote: true, class: 'glyphicon glyphicon-ok', style: "margin-right: 10px" %>
<%= item.name %>
<% if item.delegated_to != "" && item.user_id == current_user.id %>
<small>(Delegated to <%= item.delegated_to %>)</small>
<% elsif item.delegated_to != "" && item.user_id != current_user.id %>
<small>(Delegated by <%= item.user_id %>)</small>
<% end %></p>
<% end %>
<% end %>
</div>
而且_form.html.erb
偏袒其鏈接:
<div class="row">
<div class="col-xs-12">
<%= form_for [@list, @item], remote: true do |f| %>
<div class="form-group col-sm-6">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter Item Name" %>
</div>
<div class="form-group col-sm-6">
<%= f.label 'Delegate To (Not Required)' %>
<%= f.text_field :delegated_to, class: 'form-control', placeholder: "Enter an Email Address" %>
</div>
<div class="text-center"><%= f.submit "Add Item to List", class: 'btn btn-primary' %></div>
<% end %>
</div>
</div>
這裏是在items_controller
的create
方法:
def create
@list = List.friendly.find(params[:list_id])
@item = @list.items.new(item_params)
@item.user = current_user
@new_item = Item.new
if @item.save
flash[:notice] = "Item saved successfully."
else
flash[:alert] = "Item failed to save."
end
respond_to do |format| <<<<ERROR CALLED ON THIS LINE
format.html
format.js
end
end
而這裏是我的create.js.erb
file:
<% if @item.valid? %>
$('.js-items').prepend("<%= escape_javascript(render(@item)) %>");
$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: { list: @list, item: @new_item }) %>");
<% else %>
$('.flash').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button><%= flash.now[:alert] %></div>");
$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: { list: @list, item: @item }) %>");
<% end %>
任何人有任何想法,爲什麼我得到這個?我試圖從items_controller
中刪除format.html
行,但我得到了一個無法識別的格式錯誤。
刪除format.html,你肯定不需要它。然而,嘗試註釋掉你的create.js.erb文件,但留下一個簡單的console.log來查看錯誤是否來自文件 –
沒有'format.html'我在''ActionController :: UnknownFormat'上得到' respond_to do | format |'行。 (即使使用'console.log'而不是js文件內容。) – Liz
您的表單未成功以JS格式請求。也就是說,'remote:true'選項沒有正確處理。檢查此問題的可能解決方案:http://stackoverflow.com/questions/4227775/rails-form-for-remote-true-is-not-calling-js-method – sealocal