Question

class Project < ActiveRecord::Base
  belongs_to :user

class User < ActiveRecord::Base
  has_many :projects

Projects recieves user_id of one who created specific project.

ID is everything is known about User in Project.

I need to display name of the user, assigned to project, not only id integer of that user. I've tryed to hardcode it like this:

def assigned_user
  User.where(:id == @project.user_id).name
end
Was it helpful?

Solution

You can access user by following, you don't need to explicitly run query for this.

@project.user

OTHER TIPS

If you are trying to display it in the view say index.html.erb,then i simply do this

#projects_controller.rb

def index

@projects = Project.all

end

Then in the view

#index.html.erb
@projects.each do |project|

<%= project.user.name if user.name.present? %>

<%end%>

If the relationship is working then it is easy:

<%= @project.user.try(:name) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top