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.
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!
尝试如下:
Skill.includes(:user_skills).where.not(user_skills: {users: {id: current_user.id}})
Skill.joins("LEFT OUTER JOIN user_skills ON skills.id = user_skills.skill_id").where("user_skills.user_id != #{current_user.id}")
希望这可以帮助。
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.