使用ajax时未定义的方法`item_path'

时间:2016-03-13 07:10:49

标签: javascript jquery ruby-on-rails ajax

我正在尝试更新我的创建item操作以使用Ajax,但我得到了undefined method item_path`的错误,这是我在以常规html格式回复之前没有得到的错误。该项目已创建并保存,但ajax似乎无法正常工作。

这是我的_from partial:

   <%= form_for [@user, item], remote: true do |f|%>
      <div class="form-group">
        <%= f.label :name, class: 'sr-only' %>
        <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
      </div>
      <%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %>
    <% end %>

项#创建:

  def create
    @item = Item.new(item_params)
    @item.user = current_user

    if @item.save
      flash[:notice] = 'Item saved successfully.'
    else
      flash[:alert] = 'Item not saved. Title is too short or missing. Please try again.'
    end
    respond_to do |format|
      format.html
      format.js
    end
  end

create.js.erb:

$('.js-items').prepend("<%= escape_javascript(render(@item)) %>");
   $('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: {user: @user , item: @item }) %>");

用户#show view

<div class='new_item'>
<%= render :partial => 'items/form', :locals =>{:item => Item.new , :user => @user} %>
</div>
<div class='js-items'>
  <%= render @user.items %>
</div>

路线:

user_items GET    /users/:user_id/items(.:format)          items#index
                     POST   /users/:user_id/items(.:format)          items#create
       new_user_item GET    /users/:user_id/items/new(.:format)      items#new
      edit_user_item GET    /users/:user_id/items/:id/edit(.:format) items#edit
           user_item GET    /users/:user_id/items/:id(.:format)      items#show
                     PATCH  /users/:user_id/items/:id(.:format)      items#update
                     PUT    /users/:user_id/items/:id(.:format)      items#update
                     DELETE /users/:user_id/items/:id(.:format)      items#destroy

错误即将进入rails s:

ActionView::Template::Error (undefined method `item_path' for #<#<Class:0x007fa4f0d30cd8>:0x007fa4f31b26b0>):
    1: <%= form_for [@user, item], remote: true do |f|%>
    2:   <div class="form-group">
    3:     <%= f.label :name, class: 'sr-only' %>
    4:     <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
  app/views/items/_form.html.erb:1:in `_app_views_items__form_html_erb__331698480542899910_70173200751480'
  app/views/items/create.js.erb:2:in `_app_views_items_create_js_erb___3618987352886002527_70173200313760'
  app/controllers/items_controller.rb:17:in `create'

1 个答案:

答案 0 :(得分:0)

做那样的事。

<%= form_for [@user, item], user_items, remote: true do |f|%>

如果不起作用,请运行

rake routes
在终端

看看你的路径是什么。