2017-12-27 25 views
1

タスク項目(_form.html.erb)を送信するためにフォームpartialを含めるときに、私のユーザ#showでNoMethodErrorを実行しています。私の他のpartial(_item.html.erb)は適切にレンダリングされています。私のアイテムモデルと私のユーザーモデルはお互いに関連していて、ユーザーhas_many:アイテムとアイテムbelongs_to:userです。NoMethodError in users#show(Ruby Rails)

すべてのご協力をいただければ幸いです。以下は

は、以下の私の端子出力

ActionView::Template::Error (undefined method `items_path' for #<#<Class:0x007fefeca61dd0>:0x007fefeca58b18> 
Did you mean? items_create_path): 
    1: <h4> Create a new to-do item </h4> 
    2: 
    3: <%= form_for @item do |f| %> 
    4: <%= f.label :name %> 
    5: <%= f.text_field :name, class: 'form-control', placeholder: "Enter task here" %> 

アイテムコントローラ

class ItemsController < ApplicationController 

    def new 
     @item = Item.new 
    end 

    def create 
     @item = Item.new 
     @item.user = current_user 
     @item.name = params[:item][:name] 

     if @item.save 
      flash[:notice] = "Item saved" 
      redirect_to @item 
     else 
      flash.now[:alert] = "Item was not created, please try again." 
      render :new 
     end 
    end 
end 

ユーザーコントローラー

class UsersController < ApplicationController 


    def show 
    if !current_user.nil? 
     @user = current_user 
     @item = Item.new 
     @items = @user.items 
    else 
     redirect_to new_user_registration_path 
    end 
    end 
end 
がある私のroutes.rbを

Rails.application.routes.draw do 
    get 'welcome/index' 

    get 'welcome/about' 

    root 'users#show' 

    resources :users do 
    resources :items, only: [:new, :create] 
    end 


    devise_for :users 
    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 
end 

です0

ユーザー#は、あなたのitemsルートがusers下にネストされ

<h2> Your to-do list</h2> 


    <div class="col-md-8"> 
    <div class='items'> 
     <%= render partial: "items/item", local: { item: @item} %> 
    </div> 
    </div> 
    <div class="col-md-8"> 
    <div class='new-item'> 
     <%= render partial: "items/form", local: { item: @item } %> 
    </div> 
    </div> 
+0

変更 '資源:アイテムのみ:[:、新しい:作成]'リソース 'へ:items、only:[:new、:create、:index] ' – Anthony

答えて

1

をごroutes.rbファイルでは、nested resourceとして定義されている項目があります。端末でこのコマンドを実行すると、すべてのルートを確認できます。rake routesあなたのルートの

は、具体的には、あなたが言う:

resources :users do 
    resources :items, only: [:new, :create] 
end 

は、これはあなたにGET /users/:user_id/items/newPOST /users/:user_id/itemsのルートを与えるだろう。しかし、あなたのフォームでは、これをやろうとしているようです:<%= form_for @item do |f| %>。あなたは、それ自身で項目に定義された経路を持っていません。ユーザーにも提供する必要があります。

フォームのためにこれを試してください:あなたのItemsController

<%= form_for [@user, @item] do |f| %> 

そして、このような何か:

class ItemsController 
    def new 
    @user = current_user 
    @item = Item.new 
    end 
end 
+0

ありがとう、あなたの説明は明確で、私の問題を解決するのを助けました! –

1

ページを表示します。したがって、ユーザとアイテムの両方をform_forに渡す必要があります。このような

何かはおそらく動作します:

<%= form_for(current_user, @item) do |f| %> 
関連する問題