4

I have a habtm relationship (assignments < assignments_candidates > candidates)

I want to be able to delete one candidate off an assignment. here is my code so far

 @assignment = Assignment.find(:first,
  :joins => :candidates,
  :select => "assignments_candidates.*",
  :conditions => ["assignments_candidates.candidate_id = ? AND assignments_candidates.assignment_id = ?", 
    params[:candidate_id], params[:assignment_id]]
  )
  @assignment.destroy

At the moment all i think this does is destroy the object not the record in the intersection table

any ideas ?

Thanks, Alex

Alex
  • 6,205
  • 7
  • 43
  • 53

2 Answers2

13

Here is how I did it for future reference.

  assignment = Assignment.find(params[:assignment_id])
  candidate = assignment.candidates.find(params[:candidate_ids])
  assignment.candidates.delete(candidate)
Alex
  • 6,205
  • 7
  • 43
  • 53
  • Wish I saw this before I blew out my entire Role from like everywhere! fwiw googlers, `assignment.candidates.first.destroy` will not work, you'll delete every Candidate record. don't know why yet, but it sucks. – pjammer Dec 15 '12 at 19:16
-1

Have you added a :dependent => :destroy qualifier to the has_many (or has_and_belongs_to_many) relationships the associated models?

bjg
  • 7,457
  • 1
  • 25
  • 21
  • No I haven't. there is multiple candidates attached to an assignment but I only want to be able to remove one of them at a time – Alex Jul 28 '10 at 12:11
  • @Alex You could use an `after_destroy` callback to clean out the join table record. This runs transactionally with your destroy so it should be safe. See http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M001385 – bjg Jul 28 '10 at 12:36