aforalegria
aforalegria

Reputation: 370

One-to-many associations. How to refer to associated model parameter through id

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

Upvotes: 0

Views: 33

Answers (3)

Szymon
Szymon

Reputation: 21

If the relationship is working then it is easy:

<%= @project.user.try(:name) %>

Upvotes: 0

Pavan
Pavan

Reputation: 33542

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%>

Upvotes: 0

Saurabh
Saurabh

Reputation: 73589

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

@project.user

Upvotes: 2

Related Questions