[Rails] has_and_belongs_to_many problem

Rick Olson technoweenie at gmail.com
Tue Mar 1 15:01:52 GMT 2005


I'm having a problem with a has_and_belongs_to_many (habtm)
association between two models with extra attributes.  I'm writing a
comic book database, and each issue has many creators on it.  Thing
is, some creators perform multiple duties.  They may write one issue,
draw another, etc.

However, if I add a creator twice to an issue and try to delete it, it
removes both creators:
@issue.creators.delete(@creator)

rabble from #rubyonrails suggested adding multiple habtm associatings
in the Issue object.  Here's how they look:

class Issue < ActiveRecord::Base
  has_and_belongs_to_many :creators
  has_and_belongs_to_many :writers,    :class_name=>'Creator',
    :association_foreign_key=>'creator_id', :conditions=>'creator_job_id=1'
  has_and_belongs_to_many :pencillers, :class_name=>'Creator', 
    :association_foreign_key=>'creator_id', :conditions=>'creator_job_id=2'
  has_and_belongs_to_many :inkers,     :class_name=>'Creator', 
    :association_foreign_key=>'creator_id', :conditions=>'creator_job_id=3'
  has_and_belongs_to_many :colorists,  :class_name=>'Creator', 
    :association_foreign_key=>'creator_id', :conditions=>'creator_job_id=4'
  has_and_belongs_to_many :letterers,  :class_name=>'Creator',
    :association_foreign_key=>'creator_id', :conditions=>'creator_job_id=5' 

class Creator < ActiveRecord::Base
  has_and_belongs_to_many :issues 

My join table looks like this:
creators_issues
  issue_id INT
  creator_id INT
  creator_job_id INT

If I use this code, it still deletes all instances of that creator:
creator = @issue.writers.find(1)
@issue.writers.delete(creator)

Do I need to specify the Delete SQL statement for the habtm
association?  I haven't seen sample code for it, so I'm assuming I
specify the whole delete statement.   Should all 3 fields in the join
table be primary keys?

Thanks for any insight anyone can provide on this matter...

-- 
rick
http://techno-weenie.net


More information about the Rails mailing list