相同数据类型的两列

相同数据类型的两列

本文介绍了脚手架 ActiveRecord:相同数据类型的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个基本的 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.

答案似乎很明显,但我在 Internet 上的任何地方都找不到.

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:相同数据类型的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 16:32