views:

31

answers:

2

hey,

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

A: 

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

bjg
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
@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
+1  A: 

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