2016-03-07 69 views
0

我有一個自聯接在我的模型:爲什麼我的has_many foreign_key協會沒有返回我期望的內容?

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

模式:

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 

我會想象player_frames返回所有共享相同player_id自我同行幀。但事實並非如此。

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 []> 

爲什麼它試圖加載player_id爲4的幀?

回答

1

我想你要找的是一個的has_many:通過

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 

這將允許你說player.frames和將返回所有在有玩家ID player_frames參考幀的記錄。

1

隨着frame_players關聯表,你將能夠撥打:

frame.players(返回所有用於給定幀的播放器)

player.frames(返回所有的幀爲給定的播放器)

(請注意,在rails慣例中,關聯表的名稱應該以按字母順序排在第一位的表名開頭)

相關問題