2014-09-06 53 views
0

我有一個has_many飛行員的船模型。飛行員可以是角色或派系。我可以使用has_many:通過關聯來對此進行建模嗎?has_many通過關聯可以是多態嗎?

class Ship < ActiveRecord::Base 
    has_many :pilots, :through => :pilot_assignments, :polymorphic => true 
    has_many :pilot_assignments 
end 

class Character < ActiveRecord::Base 
    has_many :ships, :through => :pilot_assignments 
    has_many :pilot_assignments 
end 

class Faction < ActiveRecord::Base 
    has_many :ships, :through => :pilot_assignments 
    has_many :pilot_assignments 
end 

class PilotAssignment < ActiveRecord::Base 
    belongs_to :ship 
    belongs_to :pilot, :polymorphic => true 
end 
+0

那我的答案嗎?它有效嗎?你有沒有在你的問題上找到答案? – IS04 2014-09-09 08:33:39

+0

是的,它工作得很好。 – user2002298 2014-09-09 16:53:51

回答

0

你可以嘗試這樣的:

class PilotAssignment < ActiveRecord::Base 
    belongs_to :ship 
    belongs_to :pilot, polymorphic: true 
end 

class Ship < ActiveRecord::Base 
    # i'm not sure should be there some additional options or not (like as: :pilot) 
    has_many :pilots, through: :pilot_assignments 
    has_many :pilot_assignments 
end 

class Character < ActiveRecord::Base 
    has_many :ships, through: :pilot_assignments 
    has_many :pilot_assignments, as: :pilot 
end 

class Faction < ActiveRecord::Base 
    has_many :ships, through: :pilot_assignments 
    has_many :pilot_assignments, as: :pilot 
end 

PilotAssignment應包含以下內容:pilot_typepilot_id