[英]Rails get title of associated resource by id
I have 2 models(Clients and Projects) that are connected like this: 我有2个这样连接的模型(客户和项目):
class Project < ActiveRecord::Base
belongs_to :cliente
end
class Cliente < ActiveRecord::Base
has_many :projects
end
Projects have a :cliente_id
column in its schema, so if I do: 项目在其架构中具有
:cliente_id
列,因此,如果这样做:
Project.cliente_id
I will get the cliente_id correctly. Project.cliente_id
我将正确获取cliente_id。
My doubt is, I want to get the client name from it's id, so I need something like: 我的疑问是,我想从其ID中获取客户端名称 ,所以我需要以下内容:
Project.cliente_id.name
Which is the correct way to retrieve this info? 检索此信息的正确方法是哪种?
You can get the complete Cliente
object with project.cliente
(note that the _id
is not used). 您可以使用
project.cliente
获得完整的Cliente
对象(请注意,未使用_id
)。 So you can use it like a regular Cliente
; 因此,您可以像普通的
Cliente
一样使用它; for example, to get name
just do: 例如,要获得
name
只需执行以下操作:
project = Project.find(1)
project.cliente.name
You find associated objects through the association : 您可以通过关联找到关联的对象:
project = Project.find(1) # Returns the full `project` object
project.cliente # Returns the full `cliente` object
project.cliente.name # Returns just the `name` attribute
project.cliente_id == project.cliente.id # Returns true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.