Rails forms for has_many through association using cocoon

616 views Asked by At

i have used has-many-through relation between user and skills with bridge table skills_users. I have used cocoon gem. i am getting values from skills using dropdown box on each add_association. In adding new skill the dropdown shows all the values but i want only values that have not been selected. is there any way to reject values that have already been selected from dropbox of new skills

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

class Skill < ActiveRecord::Base
 has_many :skills_users
 has_many :users, through: :skills_users
 belongs_to :skill_type
end

class User < ActiveRecord::Base
 has_many :skills_users
 has_many :skills, through: :skills_users
end

here is my drop-down box code for skills

 = f.input :skill_id, as: :select, collection: Skill.where(skill_type: skill_type.id), label_method: :name, value_method: :id,  label: false,  placeholder: 'Add Skills'
1

There are 1 answers

3
Novae On

In your controller add:

@available_skills = Skill.where(skill_type: skill_type).where("`id` not in ?", @user.skills.pluck(:id))

then in your view:

 = f.input :skill_id, as: :select, collection: @available_skills, label_method: :name, value_method: :id,  label: false,  placeholder: 'Add Skills'