user532339
user532339

Reputation:

undefined local variable or method `user' - How to get name to appear instead of number.

I have a table which list a set amount of managers. In the Manager User Id column I am trying to get the name to appear instead of the integer. I have the following relationships

User model

has_many :roles, :through => :roles_users
  has_many :projects, :foreign_key => "manager_user_id"

Projects

class Project < ActiveRecord::Base
  belongs_to :user, :foreign_key => "manager_user_id"

Index.html.erb

    <tr>


  <td><%= project.project_number %></td>
  <td><%= project.project_name %></td>
  **<td><%= user.project.manager_user_id%></td>**
  <td><center><%= link_to image_tag("icons/user.png"), project %></center></td>
  <td><center><%= link_to image_tag("icons/user_edit.png"), edit_project_path(project) %></center></td>
  <td><center><%= link_to image_tag("icons/user_delete.png"), project, :confirm => 'Are you sure?', :method => :delete %></center></td>

    </tr>

I have tried the following:

Neither of these work and I get this error: undefined local variable or method `user' for #<#:0xb14cf5c>

What is it that I am doing wrong. I used the above similar method for another table and this worked fine.

Upvotes: 0

Views: 1683

Answers (3)

Chowlett
Chowlett

Reputation: 46667

It looks from your view that you have project defined in the view, but not user. That being so, you definitely want the project.user form. That also makes sense in that a Project only has one associated User, whereas a User has multiple Projects, so user.project is an array.

Secondly, remember that manager_user_id is a member of Project, not of User, so project.user.manager_user_id won't work.

I suspect you want something like project.user.name.

Upvotes: 1

cicloon
cicloon

Reputation: 1099

What's happening here is that in project.user.manager_user_id you are accesing a field that is not in the users table, it is in the projects table, so with project.user.name you should be able to retrieve the user name.

When you make project.user Rails instantiates the user associated to that project so you have access to every method and field in the User model.

I'm assuming that you have loaded your project in your controller, but not the user, hence the error undefined local variable or method 'user' for #<#:0xb14cf5c> when you try to execute user.project.manager_user_id.

Upvotes: 0

socjopata
socjopata

Reputation: 5095

Like it's says, it's undefined.

<%= project.user.name %> should work if you've coded AR associations properly and if you have project variable available. You can also define to_s method in you User model, so when you do <%= user %> in a view, user name is displayed, instead of a "number". Again, as long as you've prepared user first.

example:

class User < ActiveRecord::Base
   def to_s
     name
   end
end

Upvotes: 1

Related Questions