I have 3 models like this-
| 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
). 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:
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:
class User < ActiveRecord::Base
has_and_belongs_to_many :skills
has_many :sub_skills, through: :skills
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.