简体   繁体   中英

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 . On the show page for the house i would like to see the tenant which has the associated house_id in its model.

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.

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. On the show page for that specific house i would like to see the associated tenant_id.

Thank you in advance

There's no reason for you to have @tenant declared. You can access @house 's related tenant object via @house.tenant and to get the id, just use @house.tenant.id .

Edit: Your associations are wrong. See: https://guides.rubyonrails.org/association_basics.html#the-types-of-associations

Because Tenant has the column house_id, it belongs_to :house .

That means that the house has_one :tenant (can also be has_many if you're into that sorta thing). Fix that, then try what I wrote above.

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