rj487
rj487

Reputation: 4634

Rails uninitialized constant error in controller

Here is my controller directory structure

controllers/
.........../dashboard
...................../admin
.........................../admin_controller.rb
.........................../item_controller.rb
........../items_controller.rb

I expect that manager can add new item, and users can see all items.

I typed rails g scaffold dashboard/admin/items to quickly generate controller with namespace.

And I modified @dashboard_admin_items = Dashboard::Admin::Item.all

to @dashboard_admin_items = Item.all

controllers/dashboard/admin/items_controller.rb

class Dashboard::Admin::ItemsController < Dashboard::Admin::AdminController
  before_action :set_dashboard_admin_item, only: [:show, :edit, :update, :destroy]

  # GET /dashboard/admin/items
  def index
    @dashboard_admin_items = Item.all

  end
...

But it threw this error enter image description here

Also, I've put this project on github.

Update

view/dashboard/admin/items/index.html.erb

<tbody>
    <% @Items.each do |i| %>
      <tr>
        <th><%= i.id %></th>
        <th><%= i.name %></th>
        <th><%= i.price %></th>
        <!-- <td><%#= link_to 'Show', dashboard_admin_item %></td> -->
        <td>
          <%= link_to 'Edit', edit_dashboard_admin_item_path(dashboard_admin_item) %>
          <%= link_to 'Destroy', dashboard_admin_item, method: :delete, data: { confirm: 'Are you sure?' } %>
        </td>
      </tr>
    <% end %>
  </tbody>

controllers/dashboard/admin/items_controller.rb

def index
    @Items = Item.all
end

Upvotes: 2

Views: 5961

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

The issue is you have two item.rb file, one under app/model/item.rb and the other under app/models/dashboard/admin/item.rb. So, there is a conflict.

To use app/model/item.rb, use it this way: ::Item.all.

::Item means you are referring to the Item class from the top level namespace i.e. app/model/item.rb.

I ran your code locally. It works fine if you change:

  def index
    @dashboard_admin_items = Item.all
  end

to:

  def index
    @Items = ::Item.all
  end

And, you are already using @Items in your app/views/dashboard/admin/items/index.html.erb

Upvotes: 3

Related Questions