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。 我如何到达那里?

我相信你可以使用has_and_belongs_to_many的选项比Alvaro的回答更优雅,尽管他的回答非常好,并且会为你class级的任何客户提供相当相同的function。

 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选项指定哪个列是链接“this side”上的类的id,而:association_foreign_key指定链接“另一侧”的类的id列。

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

这项工作适合你……

 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 

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

不确定这是否符合你所需要的100%,但我希望它至少能给你一个想法。

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

试试这个:

 >> TvShow.find(1).episodes #=> returns an array with [#] >> Episode.find(1). tv_shows #=> returns an array with [#] 

然后你可以做一些像:

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