ActiveRecord的加入表遗留数据库 [英] ActiveRecord Join table for legacy Database

查看:146
本文介绍了ActiveRecord的加入表遗留数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的工作让ActiveRecord的一起工作遗留数据库。我碰到的与连接表的问题。我有以下几点:

I have a legacy database that I'm working on getting ActiveRecord to work with. I've run into a problem with join tables. I have the following:

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(:最后一个).episodes或Episode.find(:最后一个).tv_show。我如何到达那里?

And then I have a table called tvshowlinkepisode that has 2 fields: idShow, idEpisode So I have 2 tables and a join between them (so a many to many relationship), however the join uses non-standard foreign keys. My first thought was to create a model called TvShowEpisodeLink but there isn't a primary key. The idea was that since the foreign keys are non-standard I could use the set_foreign_key and have some control. Ultimately I want to say something like TvShow.find(:last).episodes or Episode.find(:last).tv_show. How do I get there?

推荐答案

我相信你可以稍微比使用选项has_and_belongs_to_many阿尔瓦罗的回答更优雅,但他的回答是完全正常的,并会导致任何客户相当一致的功能你的类。

I believe you can be slightly more elegant than Alvaro's answer using options to has_and_belongs_to_many, though his answer is perfectly fine and will result in fairly identical functionality for any clients of your class.

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选项指定列是身份证上的这一方的链路的类,同时:association_foreign_key指定作为身份证上的另一侧的链路的类列。

Note that the :foreign_key option specifies which column is the id for the class on "this side" of the link, while :association_foreign_key specifies the column that is the id for the class on the "other side" of the link.

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

Contrast this with Alvaro's answer, this pattern should avoid instantiation of any unnecessary objects to represent the link.

这篇关于ActiveRecord的加入表遗留数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆