2009-07-24 67 views
4

我有一个遗留数据库,我正在努力让ActiveRecord工作。我遇到了连接表的问题。我有以下几点:ActiveRecord传统数据库加入表

class TvShow < ActiveRecord::Base 

    set_table_name "tvshow" 
    set_primary_key "idShow" 

end 

class Episode < ActiveRecord::Base 
    set_table_name "episode" 
    set_primary_key "idEpisode" 
end 

然后,我有一个表称为tvshowlinkepisode有2场:idShow,idEpisode所以,我有2个表和它们之间的连接(这样一个多对多的关系),但是加盟使用非标准的外键。我的第一个想法是创建一个名为TvShowEpisodeLink的模型,但没有主键。这个想法是因为外键是非标准的,我可以使用set_foreign_key并有一些控制。最终,我想说一些像TvShow.find(:last).episodes或Episode.find(:last).tv_show。我如何到达那里?

回答

8

我相信你可以稍微比Alvaro的答案使用has_and_belongs_to_many选项稍微更优雅,尽管他的回答非常好,并且会为你的班级的任何客户带来相当一致的功能。

class TvShow < ActiveRecord::Base 

    set_table_name "tvshow" 
    set_primary_key "idShow" 
    has_and_belong_to_many :episodes, 
         :join_table => "tvshowlinkepisode", 
         :foreign_key => "idShow", 
         :association_foreign_key => "idEpisode" 

end 

class Episode < ActiveRecord::Base 
    set_table_name "episode" 
    set_primary_key "idEpisode" 
    has_and_belongs_to_many :tv_shows, 
          :join_table => "tvshowlinkepisode", 
          :foreign_key => "idEpisode", 
          :association_foreign_key => "idShow" 
end 

。注意:foreign_key选项指定列是链接的“这一面”之类的ID,而:association_foreign_key规定是对“另一面”的类ID列的链接。

与阿尔瓦罗的回答对比,这种模式应该避免实例化任何不必要的对象来表示链接。

0

这种关系是一对多关系,因此您需要在表中使用belongs_to/has__many关系。如果您的数据库具有视图,则可以通过表格视图屏蔽非标准外键。

不知道这是否适合你所需要的100%,但我希望它至少给你一个想法。

+0

有趣的想法。我以前没有使用数据库视图。我没有能力更改数据库的任何内容,所以我不确定数据库视图是否可以在这里工作。关于has_and_belongs_to_many关系的主题,如果我有非标准主键,这不会破裂吗?我认为通过使用第三种模式,我可以做一个has_and_belongs_to_many_through关系。 – nixterrimus 2009-07-24 20:36:12

+0

呃在上面的回应中使得非标准外键在关键字上:关于has_and_belongs_to_many关系的主题,如果我有非标准的*外键*,这不会破裂吗? – nixterrimus 2009-07-24 20:37:50

+0

@nixterrimus,对,谢谢 – txwikinger 2009-07-24 20:38:54

4

这对你的工作......

class TvShow < ActiveRecord::Base 
    set_table_name "tvshow" 
    set_primary_key "idShow" 

    has_many :tv_show_link_episode, :foreign_key => 'idShow' 
    has_many :episodes, :through => :tv_show_link_episode 
end 


class Episode < ActiveRecord::Base 
    set_table_name "episode" 
    set_primary_key "idEpisode" 

    has_many :tv_show_link_episode, :foreign_key => 'idEpisode' 
    has_many :tv_shows, :through => :tv_show_link_episode 

end 

class TvShowLinkEpisode < ActiveRecord::Base 
    set_table_name "tvshowlinkepisode" 

    # the foreign key is named by the TvShowLinkEpisode field, 
    # the primary key name is for the primary key of the associated class 
    belongs_to :tv_show, :foreign_key => 'idShow' 
    belongs_to :episode, :foreign_key => 'idEpisode' 
end 
0

有了这个,你不需要设置表视图,实际上,表视图它不是“Rails的路”,

试试这个:

>> TvShow.find(1).episodes 
#=> returns an array with [#<Episode idEpisode: 1, test: "Episode 1">] 

>> Episode.find(1). tv_shows 
#=> returns an array with [#<TvShow idShow: 1, test: "tvshow 1">] 

然后,你可以做一些东西,如:

e = Episode.find(1) 
TvShow.find(1). episodes << e 
#=> this make the proper association