Rails 3.1 中不同对象的全局标识建模
我有一个系统,我想要 Rails 中对象的全局标识符。全局标识是在一堆对象之间共享的数字(或字母数字)。当您保存对象时,您将插入一个基于对象和 object_id 的全局标识值。
例如:
location id=3
id=15
arc_type='location'
arc_id=3
arc_value=loc-3
所以问题是我可以使用 object_type 和 object_id 的复合外键执行 has_one 吗?或者我是否需要一个外键,例如对象值、缩写名称和原始对象的 id。
或者也许使用不同的场景,例如 md5 哈希作为外键。
这是进行多态关联的候选者吗?看起来这更适合 has_many 而不是 has_one (例如图片或评论)。有没有人做过具有多态关联的 has_one ?
谢谢
编辑 - 看起来 object_id 名称是一个坏主意,所以我替换了 arc_ 这是项目的缩写
I have a system where I want a global identifier for objects in rails. The global identification is a number (or alpha-numeric) that is shared across a bunch of objects. When you save an object you will insert a global identificaiton value that is based upon an object and an object_id.
So for example:
location id=3
id=15
arc_type='location'
arc_id=3
arc_value=loc-3
So the question is can I do a has_one using a composite foreign key of object_type and object_id. Or would I need to a foreign key like the object value, a shortened name and the id of the original object.
Or perhaps use a different scenario such as an md5 hash as foreign key.
Would this be a candidate for doing a polymorphic association? It seems like that would be more appropriate for the has_many rather than has_one (such as pictuers or comments). Has anyone ever done a has_one with a polymorphic assoication?
thx
edit - looks like the object_id name is a bad idea so i've substituted arc_ which is initials of project
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定 Rails 中的复合外键,因为
has_one
关联似乎只有:primary_key
和:foreign_key
选项。请参阅此处了解更多信息。不过,我最近完成了与此非常相似的事情。在较高级别上,我向我想要唯一标识的所有模型添加了一个
uuid
字段,以及在保存时生成 UUID 的共享代码。现在每个对象都有一个唯一的标识符,我可以使用 Rail 的:primary_key
和:foreign_key
随意构建关联。细分如下:我使用 uuidtools gem 生成通用唯一的 id。
然后我在 app/models 中创建了一些辅助方法,以确保每当创建或保存 ActiveRecord 模型时都会生成并设置 UUID。
最后,我确保我感兴趣的模型具有字符串类型的
uuid
字段并设置我的关联。我希望这有帮助。
I'm not sure about the composite foreign key in Rails since the
has_one
association only seems to have:primary_key
and:foreign_key
options. See more here.I have accomplished something very similar to this recently though. At a high level, I added a
uuid
field to all the models that I want to uniquely identify along with a shared bit of code that generates the UUID on save. Now that each object has a unique identifier, I can use Rail's:primary_key
and:foreign_key
to build associations as I please. Here's the breakdown:I used the uuidtools gem to generate a universally unique id.
Then I created some helper methods in app/models to ensure that a UUID is generated and set whenever an ActiveRecord model is created or saved.
Finally, I make sure that my models of interest have a
uuid
field of type string and set up my associations.I hope this helps.