简体   繁体   中英

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

您可以通过以下方式访问用户,您不需要为此显式运行查询。

@project.user

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

如果关系正常,那么很容易:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM