Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access joined table attributes in Rails3?
    text
    copied!<p>I am having trouble accessing the attributes of a join in Rails3.</p> <p>There is two models/tables : Place and Address. One place can have many addresses (i.e. a specific street address, a "corner of" address, etc.). For historical reasons, the tables do not follow standard Rails conventions:</p> <pre><code>class Place &lt; ActiveRecord::Base set_table_name :PLACE set_primary_key :PLACE_ID has_many :addresses, :class_name =&gt; "Address", :foreign_key =&gt; :PLACE_ID end </code></pre> <p>and</p> <pre><code>class Address &lt; ActiveRecord::Base set_table_name :ADDRESS set_primary_key :ADDRESS_ID belongs_to :place, :foreign_key =&gt; "PLACE_ID" end </code></pre> <p>I am trying to get all the addresses for one particular place:</p> <pre><code>pa = Place.joins(:addresses).where(:place_id =&gt; 68) </code></pre> <p>The SQL that is generated looks fine:</p> <pre><code>pa.to_sql "SELECT [PLACE].* FROM [PLACE] INNER JOIN [ADDRESS] ON [ADDRESS].[PLACE_ID] = [PLACE].[PLACE_ID] WHERE ([PLACE].[place_id] = 68)" </code></pre> <p>The returned relation also has the right size, as that particular place has 6 addresses associated with it:</p> <pre><code>irb(main):050:0&gt; pa.size =&gt; 6 </code></pre> <p>However, the returned relation pa only contains the attributes of the Place model, it doesn't contain any attributes of the Address model.</p> <p>Pre Rails3 I used to do a find_by_sql and could access the attributes of the two joined table easily in the returned Hash, however I simply cannot get Rails3 to reveal to me the attributes from the joined Address table.</p> <p>I must be missing something very basic here - anyone care to point it out to me ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload