[英]Ruby On Rails: Accessing value from associated model
I posted on here as you guys are a lot more helpful than the books have been for me in the past! 我在这里发布,是因为你们比过去的书对我有更大的帮助! Please excuse as i am still learning.
请原谅我还在学习。
I have a Landlord MGT App which has aa House model and a Tenant Model . 我有一个房东MGT应用程序,其中有一个房屋模型和一个租户模型 。 On the show page for the house i would like to see the tenant which has the associated house_id in its model.
在房屋的显示页面上,我希望看到模型中具有关联的house_id的租户。
show page for house 显示房屋页面
.wrapper_with_padding
%h1.showheading= 'Property Information'
#house_show
%p First Line Address: #{@house.doorno} #{@house.house_title}
%p Description: #{@house.description}
%p Tenant: #{@tenant.house.tenant_id}
Currently the above line of code for Tenant does not work and pulls NULL value. 当前,上面用于Tenant的代码行不起作用,并提取NULL值。
Models 楷模
class House < ActiveRecord::Base
belongs_to :user
belongs_to :tenant
class Tenant < ActiveRecord::Base
belongs_to :user
belongs_to :house
I have nothing in my controller for show. 我的控制器中没有任何东西可供显示。
In summary the tenant table has a house_id attribute. 总之,承租人表具有house_id属性。 On the show page for that specific house i would like to see the associated tenant_id.
在该特定房屋的显示页面上,我想查看关联的tenant_id。
Thank you in advance 先感谢您
There's no reason for you to have @tenant
declared. 您没有理由声明
@tenant
。 You can access @house
's related tenant object via @house.tenant
and to get the id, just use @house.tenant.id
. 您可以通过
@house.tenant
访问@house
的相关租户对象并获取ID,只需使用@house.tenant.id
。
Edit: Your associations are wrong. 编辑:您的关联是错误的。 See: https://guides.rubyonrails.org/association_basics.html#the-types-of-associations
请参阅: https : //guides.rubyonrails.org/association_basics.html#the-types-of-associations
Because Tenant has the column house_id, it belongs_to :house
. 因为租户具有house_id列,所以它
belongs_to :house
_house belongs_to :house
。
That means that the house has_one :tenant
(can also be has_many
if you're into that sorta thing). 这意味着房子
has_one :tenant
(如果您喜欢那种东西,也可以是has_many
)。 Fix that, then try what I wrote above. 修复该问题,然后尝试我上面写的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.