简体   繁体   English

如何定义这三个模型之间的关系?

[英]How to define the relationship between these 3 models?

I have 3 models like this- 我有3个这样的模型

| User       | Skill       | SubSkills    |
|:-----------|------------:|:------------:|
| Name       |Title        |     Title    |  
| Trade      |Trade        |    Done(bool)|    

What the models should look like- 这些模型应该是什么样的?

class User < ActiveRecord::Base
  has_and_belongs_to_many :skills
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :sub_skills
end

class SubSkills < ActiveRecord::Base
  belongs_to :user #not sure
  belongs_to :skill
end

Basically skills are the same for every user of the same trade and one user has many skills. 基本上,同一行业的每个用户的技能都相同,并且一个用户拥有很多技能。 Each skill has many subskills but a subskill is done(or not) for a particular user. 每个技能都有许多子技能,但是为特定用户完成(或不完成)子技能。

Is this possible? 这可能吗? Whats a better way to design this relationship? 有什么更好的方式设计这种关系? How will the routes be defined for this? 如何为此定义路线? Like which resource will be nested under which resource? 像哪个资源将嵌套在哪个资源下?

I think you are close, but try this: 我认为您很亲密,但是请尝试以下操作:

class SubSkills < ActiveRecord::Base
  belongs_to :skill
  has_one :user, through: :skill
end

The routes could be done a number of ways: not nested, nested, shallow nesting ...etc. 路由可以通过多种方式完成:不嵌套,嵌套,浅层嵌套等。 (check out Rails Routing from the Outside In , particularly section 2.7.1 Limits to Nesting ). (查看“ 从外部进入Rails路由” ,特别是第2.7.1 Limits to Nesting2.7.1 Limits to Nesting )。 It really depends on the needs of your application. 这实际上取决于您的应用程序的需求。

You could do something like: 您可以执行以下操作:

/users/:id/skills/:skill_id/sub_skills/:sub_skill_id

..thus in your routes.rb you would have: ..因此,在您的routes.rb您将拥有:

resources :users do
  resources :skills do
    resources :sub_skills
  end
end

If you want to be able to access all sub_skills directly from the user like user.sub_skills rather than via a specific skill like user.skills.last.sub_skills you would have to add the association to the User model like this: 如果您希望能够直接从用户(如user.sub_skills访问所有sub_skills技能,而不是通过诸如user.skills.last.sub_skills类的特定技能,则必须将关联添加到User模型中,如下所示:

class User < ActiveRecord::Base
  has_and_belongs_to_many :skills
  has_many :sub_skills, through: :skills
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM