5

我有一个遗留数据库,我正在努力让 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。我如何到达那里?

4

4 回答 4

9

我相信你可以比使用 has_and_belongs_to_many 选项的 Alvaro 的答案稍微优雅一些​​,尽管他的答案非常好,并且将为你班级的任何客户带来完全相同的功能。

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。

将此与 Alvaro 的答案进行对比,此模式应避免实例化任何不必要的对象来表示链接。

于 2009-07-24T22:13:24.177 回答
5

这项工作为你...

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
于 2009-07-24T21:09:22.467 回答
0

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

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

于 2009-07-24T20:31:17.347 回答
0

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

试试这个:

>> 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
于 2009-07-24T21:31:23.810 回答