2014-09-06 61 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