【问题标题】:Polymorphic associations or belongs_to associations多态关联或belongs_to关联
【发布时间】:2013-11-26 09:40:19
【问题描述】:

在这种情况下我使用多态关联:

class Adress < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :addresses, as: :addressable
end

我现在想要的是用户拥有家庭地址和工作地址。 我可以:

class User < ActiveRecord::Base
  has_one :home_address, as: :addressable
  has_one :work_address, as: :addressable
end

但是我不知道哪个是家庭地址,哪个是工作地址​​。

我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    您有一个Addresses 表,在您的Addresses 表中保留一个字段为“addressable_type”。然后您将能够识别不同的地址。

    您可以在地址表中包含这些字段,

    t.integer :addressable_id
    t.string  :addressable_type
    

    或简化版:

    t.references :addressable, polymorphic: true
    

    谢谢

    【讨论】:

    • 是的,但是 addressable_type 对我没有帮助,因为它保存的是“用户”类。无论如何,谢谢你的帮助。
    • addressable_type 是以多态关系存储关联对象的类的字段的标准名称。您应该添加另一个字段,称为“类别”或其他内容,可以存储“工作”、“家庭”、“移动”等。
    【解决方案2】:

    您可以设置 STI。您需要在您的地址模型中创建一个type 列。

    class Adress < ActiveRecord::Base
    
    end
    
    class WorkAddress < Address
       belongs_to :user
    end
    
    class HomeAddress < Address
       belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_one :work_address
      has_one :home_address
    end
    

    【讨论】:

    • 在我看来是一个非常好的解决方案。我会试试。谢谢队友:)
    • @GustavoLobo 没问题。如果这是对你有用的答案,那么请接受它是正确的。非常感谢!
    • 这不起作用,因为它实际保存在表地址上的是用户类。无论如何,谢谢你:)
    • @GustavoLobo - 嗨,如果 STI 设置正确,它会将类名 WorkAddressHomeAddress 保存在 Address 表的 type 列中。如果您想进一步聊天,我们可以聊天:)
    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多