Sylnois
Sylnois

Reputation: 1631

Creating a correct query with joins

I am very sorry if I post such a trivial question, but I am really stuck and Google couldn't help me, maybe because I am new with Ruby on Rails.

I have two tables:
Person
id : Integer
name : String

Address
id: Integer
person_id : Integer
name : String

I would like to retrieve a Person joined with an Address. This code snippet works, but only if there is actually an address available for this person:

@person = Person.where('person.id' => params[:id])
                 .joins(:address)
                 .select('person.id as id, address.id as aid, person.name as name, address.name as aname').first

My view:

<h2><%= @person.name %></h2>
<p><%= @person.aname %></p>

Maybe I a m doing something conceptional wrong. As I said as soon as a Person has a related Address, my view displays it, otherwise if there is no Address it prints an error.

Upvotes: 0

Views: 33

Answers (1)

Uzbekjon
Uzbekjon

Reputation: 11813

You might consider using .includes(:relation) method to generate a LEFT OUTER JOIN query. Also, consider using .find(:id) method to look for a person with specific primary key. This will make your query simpler.

@person = Person.find(params[:id]).includes(:address)

Also, you may want to call address fields in your view like this:

<h2><%= @person.name %></h2>
<p><%= @person.address.try(:name) %></p>

NOTE: Calling name on address (@person.address.name) violates Law of Demeter and you should consider adding a address_name method to your Person class. In rails, you can use delegates :x, to: :y syntax.

Upvotes: 2

Related Questions