1

I am working on a rails assignment that asks that I create a list of items. I created the controller and model for item, but am still having some trouble. I keep receiving the following error:

undefined method `items_path' for 

Here is some of my code:

class ItemsController < ApplicationController
  def new
    @item = Item.new
  end

  def create
    @item = Item.new(params.require(:item).permit(:name))
     if @item.save
       flash[:notice] = "Item was saved."
       redirect_to @item
     else
       flash[:error] = "There was an error saving the item. Please try again."
       render :new
     end
   end
end

Items Model:

class Item < ActiveRecord::Base
  belongs_to :user
end

New.html.erb in items

class Item < ActiveRecord::Base
  belongs_to :user
end

Routes.rb:

Rails.application.routes.draw do
  devise_for :users
  resources :users do
    resources :items, only: [:new, :create]
  end

  get 'welcome/index'
  root :to => 'welcome#index'
end

Item.html.erb

<%= form_for @item do |f| %>
   <%= f.label :name %>
   <%= f.text_field :name %>

   <%= f.submit "Save" %>
<% end %>
Eric Park
  • 502
  • 2
  • 7
  • 23

3 Answers3

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

This will nest items route inside user. Check rake routes and you will not get this items_path

You have to define resource :items to get items_path

So if you want to use nested routes you have to update your form and controller and if not just routes resource :items

<%= form_for [@user, @item] do |f| %>
   <%= f.label :name %>
   <%= f.text_field :name %>

   <%= f.submit "Save" %>
<% end %>

and controller

def new
    @item = Item.new
    @user = current_user
end
Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
0

You've nested your items resource under users. It should be user_items_path.

nesiseka
  • 1,268
  • 8
  • 22
0

The items are nested under users, so they always must have a corresponding user. Example /users/1/item/3

If the logged user is the one creating items, your form should look like this:

<%= form_for [current_user, @item] do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.submit "Save" %>
<% end %>

If you can create items for other users, you have to create a @user instance in the new action of the controller and then change current_user for @user

Puce
  • 1,003
  • 14
  • 28