旧数据库的 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 的内容。 我如何到达那里?
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信您可以使用 has_and_belongs_to_many 选项比 Alvaro 的答案稍微优雅一些,尽管他的答案非常好,并且将为您班级的任何客户带来相当相同的功能。
请注意,:foreign_key 选项指定哪一列是链接“这一侧”的类的 id,而 :association_foreign_key 指定哪一列是链接“另一侧”的类的 id。
与阿尔瓦罗的答案相比,这种模式应该避免实例化任何不必要的对象来表示链接。
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.
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.
Contrast this with Alvaro's answer, this pattern should avoid instantiation of any unnecessary objects to represent the link.
这项工作为你...
This work for you...
该关系是一对多的,因此您需要在表中使用belongs_to/has__many 关系。 如果您的数据库有视图,您可以通过表视图屏蔽非标准外键。
不确定这是否 100% 符合您的需求,但我希望它至少能给您一个想法。
The relationship is one-to-many so you need to use the belongs_to/has__many relationship in the tables. If your database has views, you could mask the non-standard foreign keys by a view for the tables.
Not sure if that fits 100% what you need, but I hope it at least gives you an idea.
有了这个,你不需要设置表视图,实际上,表视图它不是“Rails Way”,
试试这个:
然后你可以做一些类似的事情:
With this, you don't need to set table views, actually, tables views it's not "The Rails Way",
Try this:
Then you can do some stuff like: