Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAustin Klenk
4,399 PointsUndefined 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)
end
added
def show
@departments = Department.find(params[:id])
end
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| %>
<tr>
<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>
</tr>
<% 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
36,441 PointsShow page uses singular instance variable, controller gives it a plural name. You have to decide which one you want in both.