Stephen Horvath
Stephen Horvath

Reputation: 5588

Why is my has_many foreign_key association not returning what I expect?

I have a self join on my model:

class Frame < ActiveRecord::Base
  has_many :player_frames, class_name: 'Frame', foreign_key: 'player_id'
  belongs_to :player
end

Schema:

  create_table "frames", force: :cascade do |t|
    t.integer  "number"
    t.integer  "player_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "players", force: :cascade do |t|
    t.integer  "number"
    t.integer  "game_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

I would imagine player_frames to return all of the peer Frames that share the same player_id as self. But this doesn't be the case.

0> player_id
=> 1

0> player_frames
  Frame Load (0.4ms)  SELECT "frames".* FROM "frames" WHERE "frames"."player_id" = $1  [["player_id", 4]]
=> #<ActiveRecord::Associations::CollectionProxy []>

Why is it trying to load frames with player_id of 4?

Upvotes: 0

Views: 45

Answers (2)

Orsay
Orsay

Reputation: 1130

With a frame_players association table you will be able to call :

frame.players (return all the players for the given frame)

player.frames (return all the frames for the given player)

(Note that in rails conventions the name of your association table should begin by the name of the table that comes first in alphabetical order )

Upvotes: 1

toddmetheny
toddmetheny

Reputation: 4443

I think what you're looking for is a has_many :through

class Player
  has_many :player_frames
  has_many :frames, through: :player_frames
end

class Frame
  has_many :player_frames
  has_many :players, through: :player_frames
end

class PlayerFrames
  belongs_to :player
  belongs_to :frame
end

This will allow you to say player.frames and will return all the frame records referenced in player_frames that have that player id.

Upvotes: 1

Related Questions