0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @RichardLegacy thanks for the answer. I tried this but get an error 'undefined method `id' for nil:NilClass' i have checked and this particular property has a house_id field with the particular house.
Great stuff! Worked a treat. I need to build my knowledge on rails associations for sure!
The 'guides.rubyonrails.org` articles are all VERY good. Really recommend reading through them all once and then coming back to them whenever you need them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.