[英]Retrieve information from associated model
I have 3 models: 我有3种型号:
class Brand
attr_accessible :obs, :site, :title
has_many :equipments
end
class Equipment
attr_accessible :brand_id, :category_id, :lending_id
belongs_to :brand
has_many :lendings
end
class Lending
attr_accessible :equipment_id
belongs_to :equipment
end
I'm trying to show the brand of an associated equipament: Brand: <%= @lending.equipment.brand %> that command show this: Brand:0xab7f2c8 我试图显示相关设备的品牌:品牌:<%= @ lending.equipment.brand%>该命令显示以下内容:Brand:0xab7f2c8
As you can see, there's no association between brand and lending models and for me its strange if i do that. 如您所见,品牌和借贷模式之间没有关联,如果这样做,对我来说这很奇怪。 I want to use the equipment/brand association to retrieve the :title information and show it on my lending view. 我想使用设备/品牌关联来检索:title信息并将其显示在我的借阅视图中。
Can anyone help me? 谁能帮我?
You can either use a delegate in Lending
: 您可以在Lending
使用委托:
delegate :brand, :to => :equipment, allow_nil: true
Or you can setup a has-one-through association in Lending
: 或者,您可以在Lending
设置一个具有一次性联系的关联:
has_one :branch, :through => :equipment
Either way, you can now call branch
directly from a Lending
instance, and work on it (almost) as if it were a regular association. 无论哪种方式,您现在都可以直接从Lending
实例调用branch
,并(几乎)像对待常规关联一样对其进行处理。
Use delegate
使用delegate
class Lending
attr_accessible :equipment_id
belongs_to :equipment
delegate :brand, :to => :equipment, :allow_nil => true
end
now you can use 现在您可以使用
<%= @lending.brand.title%>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.