Rails:我可以使用带有非整数主键的多态引用吗?
我有一个使用 UUID 作为主键的数据库,如下所示:
create_table "my_table", :id => false, :force => true do |t|
t.string "id", :limit => 36
end
但是,当我尝试使用 :references 作为该表的外键时,它会生成 ID 的整数列。是否可以指示 :references 处理非整数 ID?我对引用表的迁移是这样的:
create_table "child_table" :id => false, :force => true do |t|
t.string "id", :limit => 36
t.references :my_table
end
我知道我可以手动创建 :my_table_id
和 :my_table_type
列,但我想知道 :references 是否
可以在这些情况下发挥其魔力,这样我就不必在整个代码中显式处理 id+type 了。
I have a database that uses UUIDs as primary keys, like this:
create_table "my_table", :id => false, :force => true do |t|
t.string "id", :limit => 36
end
However, when I try to use :references for foreign keys to that table, it generates integer columns for the ID. Can :references be instructed to deal with a non-integer ID? My migration for the referring table is like this:
create_table "child_table" :id => false, :force => true do |t|
t.string "id", :limit => 36
t.references :my_table
end
I know that I could just manually create :my_table_id
and :my_table_type
columns, but I'm wondering whether :references
can be made to do its magic under these circumstances so that I don't have to handle the id+type explicitly throughout my code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Rails 4.2 开始,引用时添加了 :type 选项
例如:
source: https://github.com/rails/rails /拉/16231
A :type option has been added when referencing since Rails 4.2
For example:
source: https://github.com/rails/rails/pull/16231
不,在撰写本文时,
references
仅创建整数列。我确信您可以重写
references
方法来执行您想要的操作。但在我看来,您最好明确指定 UUID 列并键入列。这样代码就可以清楚地了解幕后发生的事情。Nope,
references
only creates integer columns as of this writing.I'm sure you could override the
references
method to do what you want. But IMO you'd be better off specifying your UUID columns and type columns explicitly. That way the code is clear about what is going on behind the scenes.