rails 5 个 HABTM 协会
rails 5 HABTM associations
如何获得 current_user 的 UserSkill table 中尚不存在的所有技能?
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
我试过这个:
@available_user_skills = Skill.includes(:user_skills).where.not( :user_skills => { :user_id => current_user } )
它只加载技能 table 中存在的所有技能。
我想你正在找这个
user_skill_ids = UserSkill.where(user_id: current_user.id).pluck(:skill_id)
not_user_skills = Skill.where.not(id: user_skill_ids)
或一行
not_user_skills = Skill.where.not(id: current_user.skills.pluck(:id))
这里not_user_skills是不属于current_user
的技能
希望对您有所帮助!
尝试如下:
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}")
希望这对您有所帮助。
如何获得 current_user 的 UserSkill table 中尚不存在的所有技能?
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
我试过这个:
@available_user_skills = Skill.includes(:user_skills).where.not( :user_skills => { :user_id => current_user } )
它只加载技能 table 中存在的所有技能。
我想你正在找这个
user_skill_ids = UserSkill.where(user_id: current_user.id).pluck(:skill_id)
not_user_skills = Skill.where.not(id: user_skill_ids)
或一行
not_user_skills = Skill.where.not(id: current_user.skills.pluck(:id))
这里not_user_skills是不属于current_user
的技能希望对您有所帮助!
尝试如下:
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}")
希望这对您有所帮助。