0

I have a database of skills that relate to each other as prerequisites to each other. In an index of skills, I'd like to be able to search through other skills and add 1 or more as prerequisites. It's important to note that I ONLY want the user to be able to add prerequisites, not remove them, as that's taken care of through an up-down voting system. I'm using JQuery Tokeninput and actually have all of this working except for one thing: I can't figure out how to only add prerequisites, rather than replacing all the prerequisites for a particular skill on submit.

Models:

class Skill < ActiveRecord::Base
  attr_accessible :skill_relationship_attributes, :prereq_tokens      

  has_many :skill_relationships
  has_many :prereqs, :through => :skill_relationships
  has_many :inverse_skill_relationships, :class_name => 'SkillRelationship', :foreign_key => "prereq_id"
  has_many :inverse_prereqs, :through => :inverse_skill_relationships, :source => :skill

  attr_reader :prereq_tokens

  accepts_nested_attributes_for :skill_relationships, :allow_destroy => true

  def prereq_tokens=(ids)
    self.prereq_ids = ids.split(",")
  end
end

class SkillRelationship < ActiveRecord::Base
  attr_accessible :skill_id, :prereq_id, :skill_attributes, :prereq_attributes

  belongs_to :skill
  belongs_to :prereq, :class_name => 'Skill'
end

JQuery:

$('#skill_prereq_tokens').tokenInput('/skills.json',
  { theme:'facebook',
    propertyToSearch:'title',
    queryParam:'search',
    preventDuplicates:'true'
  });

View:

<%= simple_form_for skill do |f| %>
  <%= f.input :prereq_tokens %>
  <%= f.submit %>
<% end %>
Chris Fritz
  • 1,922
  • 1
  • 19
  • 23

1 Answers1

0

I feel a bit silly for not getting this before, but I solved my problem by changing how prereq_tokens became prereq_ids in my Skill model.

I just changed this:

def prereq_tokens=(ids)
  self.prereq_ids = ids.split(",")
end

to this:

def prereq_tokens=(ids)
  self.prereq_ids += ids.split(",")
end

That's it. That little plus sign before the equals sign. I hope this helps anyone else who codes too long without a break!

Chris Fritz
  • 1,922
  • 1
  • 19
  • 23