0
我需要連接2個玩家連接桌子。該連接表必須具有活動標誌,並且可能會有更多屬性前進。我希望能夠將2 Players
與PlayerLink
和active_player
和passive_player
相關聯,所以我可以說player_link.active_player.name
。在Rails中設計關係的建議
我試過以下,但沒有得到我想要的行爲。也許我錯過了一些愚蠢的東西,或者錯誤地接近它。
module V1
class Player < ActiveRecord::Base
belongs_to :player_link
end
end
module V1
class PlayerLink < ActiveRecord::Base
has_one :active_player, class_name: "Player", foreign_key: :active_player_id
has_one :passive_player, class_name: "Player", foreign_key: :passive_player_id
end
end
schema.rb
項:
create_table "player_links", force: true do |t|
t.integer "active_player_id"
t.integer "passive_player_id"
t.boolean "active"
t.datetime "created_at"
t.datetime "updated_at"
end
測試查詢炸燬:
V1::PlayerLink.where(active: true).each do |l|
l.active_player.update_attribute(:foo, bar)
l.passive_player.update_attribute(:foo, bar
end
與錯誤:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: players.active_player_id: SELECT "players".* FROM "players" WHERE "players"."active_player_id" = ?
獎勵:爲什麼Rails的查詢agains players
?