Reputation: 797
category/show.html.erb
<body class="home">
<% @category.subcategories.each do |subcategory| %>
<%= link_to subcategory.name, subcategory.id %>
<% end %>
Throws NoMethodError in Category#show undefined method `model_name' for Fixnum:Class
The URL is http://example.com:3000/category/11
Routes.rb
FirstApp::Application.routes.draw do
root 'category#index'
resources :category
end
Category controller
class CategoryController < ApplicationController
def index
@categories = Category.all
end
def new
end
def show
@category = Category.find params[:id]
end
end
Subcategory controller is empty
class SubcategoryController < ApplicationController
def create
end
def new
end
def show
@category = Category.find(params[:id])
end
end
The method category.subcategories works in the console. I'm probably missing something obvious.
Upvotes: 2
Views: 2881
Reputation: 47472
Change
<%= link_to subcategory.name, subcategory.id %>
to
<%= link_to subcategory.name, subcategory %>
Upvotes: 0
Reputation: 51151
Try this:
<%= link_to subcategory.name, subcategory %>
When you pass subcategory.id
as a second argument to this method, Rails try to guess the path from Fixnum
you passed. Since it's impossible, the error is raised.
You should also add
resources :subcategories
to your routes.rb and rename your SubcategoryController
to SubcategoriesController
.
and in SubcategoriesController#show
should be:
@subcategory = Subcategory.find(params[:id])
Upvotes: 3
Reputation: 12320
could you please try this
<% @category.subcategories.each do |subcategory| %>
<%= link_to subcategory.name, subcategory_path(subcategory) %>
<% end %>
and in controller hope you have a model subcategory with many to many
relationship with category
def show
@category = SubCateogry.find params[:id]
end
In routes
resources :subcategories
Upvotes: 0