Reputation: 367
Im quite new to rails and stumpled upon a challenge..
I have 3 models, user, skill and user_skill.
UserModel
has_many :user_skills
has_many :skills, :through => :user_skills
UserSkillModel
belongs_to :user
belongs_to :skill
SkillModel
has_many :user_skills
has_many :users, :through => :user_skills
In my UserSkill i have a column called level, so the idea is that when i assign a user a skill i can define a skill level. The whole association setup is working as far as i can tell, but im not sure how i get the level associated with the @user.skills result.
attributes:
id: 1
name: Rails
created_at:
updated_at:
Upvotes: 0
Views: 383
Reputation: 7784
I think this is a nice solution for your problem:
class UserSkill
belongs_to :user
belongs_to :skill
delegate :name, :to => :skill
end
example:
@user_skills = @user.user_skills(:include => :skill).all
@user_skills.each do |user_skill|
user_skill.name
user_skill.level
end
Upvotes: 2
Reputation: 7033
Here's how you can go about it:
@user.user_skills.each do |user_skill|
skill_name = user_skill.skill.name
level = user_skill.level
end
This will get you the name of the skill and the level of the skill for each skill the user has.
If you have a user and a skill and want to find the level you can create a user function
def skill_level(skill)
self.user_skills.find_by_skill(skill).level
end
then just call
@user.skill_level(skill)
Upvotes: 0