2017-01-24 116 views
0

我在一个项目中有一个问题,我有一个称为域的模型和另外两个称为知识和练习的模型。 域名保留知识和练习的共同属性和关联,除此之外,知识和练习保留他拥有的属性和关联。 域名可以是知识或运动。继承红宝石控制器

我想创建然后模型和移民之间的关系如下:

class Domain < ApplicationRecord 
    has_one :knowledge 
    has_one :exercise 
end 

class Knowledge < ApplicationRecord 
    belongs_to :domain 
end 

class Exercise < ApplicationRecord 
    belongs_to :domain 
end 

它的工作现在,但我不知道这是正确的做法,我不知道是什么步骤按照创建知识和练习的控制器方法,因为我必须先创建一个相应的域。

你能告诉我正确的方法或告诉我可以搜索什么来找到它吗?

非常感谢您的帮助!

+0

你也可以考虑使用STI。 – max

回答

1

具有KnowledgeExercise同时在Domainhas_one关系不符合该声明域可以是知识或练习

我建议创建一个多态关系来更好地处理这种情况。

class Domain < ApplicationRecord 
    belongs_to :implementation, polymorphic: true 
end 

class Knowledge < ApplicationRecord 
    has_one :domain, as: 'implementation' 
end 

class Exercise < ApplicationRecord 
    has_one :domain, as: 'implementation' 
end 

这样,domain只能有一个执行(无论是knowledge,或exercise,并且将满足您的需求更好。当然,你可以重命名implementation到任何你喜欢的。

希望这回答你的问题