Brittany
Brittany

Reputation: 1439

uninitialized constant UsersController::Categories

I have a page (mytestpage.html.erb) located at app/views/users/mytestpage.html.erb.

I've created a new table in my database called "Categories".

I'm trying to create a dropdown menu that lists all of the categories (:title string) on my mytestpage.html.erb page and I'm getting this error:

uninitialized constant UsersController::Categories

Here is my users_controller.rb

def mytestpage
  @user = User.new
  @categories = Categories.new
end

And here is my users/mytestpage.html.erb file:

<%= form_for categories do |f| %> 
     <%= f.collection_select(:title, Categories.all, :title, :description) %>
     <% end %>

I assume that I wouldn't define @categories in my user_controller.rb (even though the file is located in my users folder - while I tried it, doing so throws me the same error).

Upvotes: 1

Views: 597

Answers (2)

Andrew Hendrie
Andrew Hendrie

Reputation: 6415

1. Use the instance variable instead of a constant in your view at app/views/users/mytestpage.html.erb:

<%= form_for categories do |f| %> 
     <%= f.collection_select(:title, @categories, :title, :description) %>
<% end %>

You're currently referencing a constant in the view. What you should be doing is referencing the instance variable that you've created in users_controller.rb

Instance variables are prefixed with @ and are made available in the view that corresponds with the controller action that they are defined in.

2. Change your instance variable definition to this:

@categories = Category.new

or

@categories = Category.all

Right now you've got it defined as Categories.new and I don't think that's what you want to do - that is likely also why you're getting the error.

(depending on what you want to do - I feel like you might want to show all of the categories in you select tag? correct me if I'm wrong.)

Upvotes: 1

Spacepotato
Spacepotato

Reputation: 144

It looks like you haven't created a model file for your Categories table. Something as simple as this:

class Category < ActiveRecord::Base

end

Should do the trick.

You will notice that I have named the class Category instead of Categories and this is due to the fact that Rails expects class names in singular form (eg User instead of Users) as it can infer the pluralised table name from the singular class name.

Upvotes: 1

Related Questions