ruby-on-rails – 如何最好地将地址与rails中的多个型号相关联?
This question在SO上似乎与我的问题有关,但我不知道我的问题是如何回答的.
地址可以属于多个模型(UserProfile和Event) user_profiles(id) events(id) 实现地址表的选项: >地址(id,user_profile_id,event_id) 注意: 我可以做这样的表,我想: user_profiles(id,address_id) events(id,address_id) 但是,这意味着相同的address_id可以属于不同的模型. @current_user_profile.address = some_new_address #this would have changed the address for both the user_profile *and* the event @current_user_profile.save 解决方法
一种方式是标准的Rails多态:
class Address belongs_to :addressable,:polymorphic => true end class UserProfile has_one address,:as => :addressable end class Event has_one address,:as => :addressable end 这可能是你所感到的尴尬的感觉,就是你不能用Rails风格的多态关系创建一个db级约束.替代方案(由Dan Chak在Enterprise Rails提出)就像您的#1选项,您确实为每种类型的关系创建一个单独的id字段.这样做不会留下未使用的字段,但它也允许约束.我可以看到两者的争论,但Rails社区一直使用AR多态性一段时间,显然取得了很大的成功.我毫不犹豫地使用它.但是,如果你的错误,你可以使用Chak的方法.这是更多的工作. :) 编辑:@ Slick86,迁移看起来像: class CreateAddresses < ActiveRecord::Migration def change create_table :addresses do |t| t.integer :addressable_id t.string :addressable_type end end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |