Sylnois Sylnois - 8 months ago 19
Ruby Question

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:


id : Integer

name : String


id: Integer

person_id : Integer

name : String

I would like to retrieve a

joined with an
. This code snippet works, but only if there is actually an address available for this person:

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

My view:

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

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


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><%= %></h2>
<p><%= @person.address.try(:name) %></p>

NOTE: Calling name on address ( 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.