Question

I am new to Ruby on Rails and set myself a little project to get to grips with it. The project is simple just a basic jobs board where a person can post a job. I Also want to have users to have a skills section. I have the user created along with sessions and also got the jobs created so the user can post a job and only edit their own ect. I now want the user to add skills associated to themselves. I am confused on how I can achieve this in terms of when viewing a users profile in the user view, it will also display their skills. I assume I need t create a new scaffold for the skill and create a relationship user has_many skills ect. Is this along the right lines? Also how can i get the skills to be shown on the users profile.

Any help would be really appreciated.

Was it helpful?

Solution

You are definitely on the right track. What you need to do it setup the Skill model/scaffold to have in addition to its usual fields, a user_id of type integer. This is to store the foreign key of the user that the skill be. Then you can setup the Skill model to have a belongs_to association with the user. So in the code you can do things like:

@skill.user
@user.skills

Essentially, once a user has skills connected to them, it's relatively easy to show them on /user/1 for example

<p><%= @user.name %> has the following skills</p>
<ul>
<% @user.skills.each do |skill| %>
  <li><%= skill.title %></li>
<% end %>
</ul>

I'm just guessing on the attribute names there, but you get the idea.

However

To be completely honest, I would actually attack this from a many to many methodology. Where you have two separate models, Skill and User. Then you have one in between called SkillsUser (lacking the ending pluralization for the table name). This means you can have a set of saved skills such as.

  • Mathematics
  • Computing
  • Programming
  • Marketing skills

And then associate the one skill record to multiple users.

class Skill < ActiveRecord::Base
  has_many :skills_users
  has_many :users, :through => :skill_users

end

class User < ActiveRecord::Base
  has_many :skills_users
  has_many :skills, :through => :skill_users

end

class SkillUser < ActiveRecord::Base
  belongs_to :skill
  belongs_to :user
end

Both models having the two has_many declarations basically allows you to still use things like:

@user.skills
@skill.users

Without having to reference the join model in between.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top