Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Austin Klenk
Austin Klenk
4,399 Points

Undefined Method 'user'

For the past 12 hours or so ive been trying to show the user in the departments index & show page. so far what i have and have done

Added user_id to departments table added user_id to the department params

    def department_params
      params.require(:department).permit(:name, :user_id)


def show
@departments = Department.find(params[:id])

Added a collection_select in the department _form partial and works perfect no errors

 <%= collection_select( :department, :user_id, User.all, :id, :email, {}, { :multiple => false } ) %>

Then i tried adding to the index page with and get the error of undefined method 'user'

    <% @departments.each do |department| %>
        <td><%= department.name %></td>
        <td><%= department.user.email %></td>

        <td><%= link_to 'Show', department %></td>
        <td><%= link_to 'Edit', edit_department_path(department) %></td>
        <td><%= link_to 'Destroy', department, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    <% end %>

Then tried adding it to the show page and i get the same error undefined method 'user'

  <%= @department.user.email %>

I went to create a new department the collection select works wonderful, i checked the department table and there is a id in the user_id column.

my models

## user.rb
belongs_to :department

## department.rb
has_many :users

and this is a little test app that i created so i know before i implement it into my main app..

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,440 Points

Show page uses singular instance variable, controller gives it a plural name. You have to decide which one you want in both.