2014-09-03 79 views
0

我需要连接2个玩家连接桌子。该连接表必须具有活动标志,并且可能会有更多属性前进。我希望能够将2 PlayersPlayerLinkactive_playerpassive_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

回答

1

这些被称为自我指涉协会 - 我第一次遇到麻烦时也遇到了麻烦。

尝试修改您的控制器逻辑如下:

module V1 
    class Player < ActiveRecord::Base 

    has_many :player_links 

    end  
end 

module V1 
    class PlayerLink < ActiveRecord::Base 

    belongs_to :player, :foreign_key => "active_player_id" 
    belongs_to :passive_player, :class_name => "Player", :foreign_key => "passive_player_id" 

    end 
end 

欲了解更多信息,请参阅RailsCast #163