Note that there are some explanatory texts on larger screens.

plurals
  1. PORails3 and ActiveRecord with legacy database: JOIN not returning other table columns
    primarykey
    data
    text
    <p>I have a legacy database that contains two different tables (tbl_players and tbl_player_ratings) that link to one another on a common column (player_key). </p> <p>My problem: With Rails3, when I attempt to retrieve PlayersRatings joined to Players, only columns from PlayerRatings are returned. However, if I execute the same SQL query at the mysql command line, columns from both tables are returned.</p> <p>For simplicity, I here provide just a few of the columns from each table.</p> <h3>tbl_players</h3> <pre><code>player_key, last_name </code></pre> <h3>tbl_player_ratings</h3> <pre><code>player_key, rating </code></pre> <p>My Rails classes representing these tables look as follows:</p> <pre><code>class PlayerRating &lt; ActiveRecord::Base establish_connection :legacy set_table_name 'tbl_player_ratings' set_primary_key "player_key" belongs_to :player, :foreign_key =&gt; 'player_key' end class Player &lt; ActiveRecord::Base establish_connection :legacy set_table_name 'tbl_players' set_primary_key "player_key" has_many :player_ratings, :foreign_key =&gt; 'player_key' end </code></pre> <p>The query that I'm running in the rails console:</p> <pre><code>PlayerRating.joins(:player).select("*").limit(1) </code></pre> <p>This returns a sole PlayerRating without any Player fields represented.</p> <p>The SQL produced by the above rails command:</p> <pre><code>SELECT * FROM `tbl_player_ratings` INNER JOIN `tbl_players` ON `tbl_players`.`player_key` = `tbl_player_ratings`.`player_key` LIMIT 1 </code></pre> <p>When I execute that exact command at the mysql command-line, all columns in both tables are returned.</p> <p>Why does Rails and ActiveRecord not do the same (return all columns in both tables)?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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