Ryan Wood <ryan.wood-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> writes:
> I have a site that is managing advertisers in a publication. Each
> issue of the publication has certain advertisers. An advertisers is
> assigned a specific advertiser index in each issue. This index could
> change from issue to issue. It is very close to a many-to-many join
> with the exception of the advertiser index. Since it''s not a
straight
> many to many join, how would I utilize ActiveRecord?
>
> **DATABASE**
>
> CREATE TABLE `advertiser` (
For better or worse, the "golden path" of Rails development is to use
plural names on tables.  You can turn this off, but I personally don''t
recommend it.  Name this table ''advertisers'' and the one below
''issues''.
>   `id` int(10) unsigned NOT NULL auto_increment,
>   `name` varchar(200) NOT NULL default '''',
>   `notes` varchar(255) NOT NULL default '''',
>   PRIMARY KEY  (`id`)
> ) ENGINE=InnoDB DEFAULT CHARSET=latin1 
>
> CREATE TABLE `issue` (
>   `id` int(10) unsigned NOT NULL auto_increment,
>   `name` varchar(45) NOT NULL default '''',
>   `publish_date` date NOT NULL default ''0000-00-00'',
One thing to think about, if you have a column named
''create_at'' then
ActiveRecord will automatically record when the issue is first
created.  Probably not the same thing as publish_date, but something
to think about.
>   PRIMARY KEY  (`id`)
> ) ENGINE=InnoDB DEFAULT CHARSET=latin1
>
> CREATE TABLE `issue_advertisers` (
Join tables need to be in alphabetical order.  This should be
''advertisers_issues''.
>   `issue_id` int(11) NOT NULL default ''0'',
>   `advertiser_index` int(11) NOT NULL default ''0'',
>   `advertiser_id` int(11) NOT NULL default ''0'',
>   PRIMARY KEY  (`issue_id`)
> ) ENGINE=InnoDB DEFAULT CHARSET=latin1
class Advertiser < ActiveRecord::Base
  has_and_belongs_to_many :issues
end
class Issue < ActiveRecord::Base
  has_and_belongs_to_many :advertisers
end
Note that you''ll need to use something like
@issue.advertisers.push_with_attributes(@attribute, {:advertiser_index
=> "foo" }) to get attributes on the join table.  However, if you
start getting too many join attributes or need to modify them much, it
may be easier to do this:
class AdvertiserIssue < ActiveRecord::Base
  belongs_to :advertiser
  belongs_to :issue
end
class Advertiser < ActiveRecord::Base
  has_many :advertiser_issues
end
class Issue < ActiveRecord::Base
  has_many :advertiser_issues
end
-- 
doug-jGAhs73c5XxeoWH0uzbU5w@public.gmane.org