Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I don't think that you can load users and profiles with join in Rails. I think that in earlier versions of Rails ( &lt; 2.1) loading of associated models was done with joins, but it was not efficient. <a href="https://stackoverflow.com/questions/1208636/rails-include-vs-joins">Here</a> you have some explanation and links to other materials.</p> <p>So even if you explicite say that you want to join it, Rails won't map it to associated models. So if you say <code>Profile.whatever_here</code> it will always be mapped to <code>Profile</code> object.</p> <p>If you still want to do what you said in question, then you can call custom sql query and process results by yourself:</p> <pre><code>p = ActiveRecord::Base.connection.execute("SELECT * FROM profiles JOIN users ON profiles.user_id = users.id LIMIT 1") </code></pre> <p>and get results row by row with:</p> <pre><code>p.fetch_row </code></pre> <p>It will already be mappet to an array.</p> <p>Your errors are because you are calling <code>first_name</code> and <code>user</code> method on <code>AciveRecord::Relation</code> object and it stores an array of <code>Profile</code> objects, not a single object. So</p> <pre><code>p = Profile.joins(:user).limit(1) p[0].first_name </code></pre> <p>shoud work.</p> <p>Better way to fetch only one record is to call:</p> <pre><code>p = Profile.joins(:user).first p.first_name p.user </code></pre> <p>But when you call <code>p.user</code> it will query database. To avoid it, you can use <code>include</code>, but if you load only one profile object, it is useless. It will make a difference if you load many profiles at a time and want to inlcude users table.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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