Search code examples
ruby-on-railshas-and-belongs-to-many

rails 5 HABTM associations


How can I get all Skills that does not already exist in the UserSkill table for current_user?

class User < ApplicationRecord
    has_many :user_skills
    has_many :skills, through: :user_skills
end

class Skill < ApplicationRecord
    has_many :user_skills
    has_many :users, through: :user_skills
   end

class UserSkill < ApplicationRecord
    belongs_to :user
    belongs_to :skill
end

I have tried this:

@available_user_skills = Skill.includes(:user_skills).where.not( :user_skills => { :user_id => current_user } )

Which just loads all Skills that exist in the Skills table.


Solution

  • I think you are looking for this

    user_skill_ids = UserSkill.where(user_id: current_user.id).pluck(:skill_id)
    not_user_skills = Skill.where.not(id: user_skill_ids)
    

    or in one line

    not_user_skills = Skill.where.not(id: current_user.skills.pluck(:id))
    

    Here not_user_skills are the skills that don't belong to the current_user

    Hope this helps!