2012-02-28 72 views
0

我正在AI競賽的網站上工作,您可以上傳pacman或ghosts控制器,他們會被評估,結果會顯示在網站上。Rails中的條件has_many foreign_key?

我有用於控制器,稱爲「代理」一個表:

class CreateAgents < ActiveRecord::Migration 
    def change 
    create_table :agents do |t| 
     t.string :ctype # either 'pacman' or 'ghosts' 
     t.references :user, :null => false 
     ... 
     t.timestamps 
    end 
    ... 
    end 
end 

每個控制器屬於一個用戶,並且它們可以是兩種類型:「吃豆」或「鬼」。

兩個控制器選擇(一個吃豆子,一個鬼魂),和他們玩遊戲,而遊戲是存儲在數據庫中:

class CreateGames < ActiveRecord::Migration 
    def change 
    create_table :games do |t| 
     t.integer :pacman_agent_id 
     t.integer :ghosts_agent_id 
     t.integer :score 
     t.timestamps 
    end 
    ... 
    end 
end 

當我要選擇讓我們說的在吃豆子劑特定的遊戲,我只是做一個:

Game.first.pacman 

使用belongs_to的用適當的foreign_key:

class Game < ActiveRecord::Base 
    belongs_to :pacman, class_name: 'Agent', foreign_key: 'pacman_agent_id' 
    belongs_to :ghosts, class_name: 'Agent', foreign_key: 'ghosts_agent_id' 
end 

但是,我無法弄清楚如何做相反的事情,即爲特定的代理人選擇遊戲。

我願做這樣的事情:

Agent.first.games 

因此,這將返回遊戲特定的控制器,獨立如果它的吃豆子鬼或控制器。

這是我試過,但它不工作:

class Agent < ActiveRecord::Base 
    belongs_to :user 
    has_many :games, foreign_key: (:ctype == 'pacman' ? 'pacman_agent_id' : 'ghosts_agent_id') 
end 

任何想法?也許我的數據庫設計不正確?

在此先感謝!

回答

1

任何想法?也許我的數據庫設計不正確?

是的,這是絕對不正確! xD

與其將兩個id字段添加到一個模型中,您應該使用多態關聯,該關聯還需要兩個字段,但其中一個包含類型(型號名稱),另一個包含該ID。你會發現你需要這裏的一切:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

它有點在第一時間複雜。 Theres也是關於這個主題的軌道廣播(#154)。

+0

S..t,我知道我的設計有問題。這只是我的第三週做Rails,然後我會閱讀更多有關多態關聯的知識。謝謝! – 2012-02-28 22:34:43