问题描述
另一个基本的Rails问题:
Another basic Rails question:
我有一个需要包含对完全两个不同的特定数据类型的记录的数据库表。
I have a database table that needs to contain references to exactly two different records of a specific data type.
假设的例子:我在做一个视频游戏数据库。我有一个表的公司。我想有一个确切的开发者和唯一一个发行商为每一个视频游戏条目。
Hypothetical example: I'm making a video game database. I have a table for "Companies." I want to have exactly one developer and exactly one publisher for each "Videogame" entry.
我知道,如果我想有个公司,我可以做这样的事情:
I know that if I want to have one company, I can just do something like:
script/generate Videogame company:references
不过,我需要有两家公司。我宁可不使用连接表,因为只能在给定的数据类型正好两个,我需要他们是不同的。
But I need to have both companies. I'd rather not use a join table, as there can only be exactly two of the given data type, and I need them to be distinct.
这似乎是答案应该是pretty的明显,但我找不到它的任何地方在互联网上。
It seems like the answer should be pretty obvious, but I can't find it anywhere on the Internet.
推荐答案
只是为了整理了一点东西,在你的迁移,你现在还可以做的:
Just to tidy things up a bit, in your migration you can now also do:
create_table :videogames do |t|
t.belongs_to :developer
t.belongs_to :publisher
end
既然你打电话developer_id和PUBLISHER_ID键,模型也许应该是:
And since you're calling the keys developer_id and publisher_id, the model should probably be:
belongs_to :developer, :class_name => "Company"
belongs_to :publisher, :class_name => "Company"
这不是一个大问题,但我发现,作为额外的参数社团的数量得到补充,不太清楚事情成了,所以最好坚持使用默认设置只要有可能。
It's not a major problem, but I find that as the number of associations with extra arguments get added, the less clear things become, so it's best to stick to the defaults whenever possible.
这篇关于脚手架的ActiveRecord:相同数据类型的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!