代码之家  ›  专栏  ›  技术社区  ›  Hugo

具有多态关系的活动记录获取关联模型

  •  0
  • Hugo  · 技术社区  · 8 年前

    我有这样一个多态地址模型:

    class Address < ApplicationRecord
      belongs_to :addressable, polymorphic: true
    end
    

    以及两个可能的关联,用户和朋友:

    class User < ApplicationRecord
      has_many :friends, dependent: :destroy
      has_one :address, :as => :addressable, dependent: :destroy
    end
    
    class Friend < ApplicationRecord
      belongs_to :user
      has_many :addresses, :as => :addressable, dependent: :destroy
    end
    

    我希望能够从该地址获得朋友或用户。两者都与地址模型相关。

    我怎样才能做到以下几点:

    Address.last.user
    

    Address.last.friends.first
    

    非常感谢。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Vaibhav Dhoke    8 年前
    Address.new.addressable # will give the addressed object
    # Depending what was addressed it will return User or Friend
    

    但要实现您的要求,您需要创建一个方法,并且它不会被视为一个关系(不能在联接中使用)

    class Address < ApplicationRecord
      belongs_to :addressable, polymorphic: true
    
      def user
        addressable if addressable_type == User.name
      end
    
      def friend
        addressable if addressable_type == Friend.name
      end
    end
    

    不能在类中调用关系,必须在对象上调用它们。 Address.user # will throw an error

    而且 Address 具有关系类型 belongs_to 所以你没有地址的朋友列表,你有一个地址的朋友列表。

        2
  •  1
  •   TheVinspro    8 年前

    正如您定义的多态模型。

    class Address < ApplicationRecord
      belongs_to :addressable, polymorphic: true
    end
    

    一个地址将与 User Friend

    看见 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

    对于多态关联,一个模型可以在单个关联上属于多个其他模型。

    Address.last.user or Address.first.friend
    

    在这里,您定义了地址和朋友之间的关系。

    class Friend < ApplicationRecord
      belongs_to :user
      has_many :addresses, :as => :addressable, dependent: :destroy
    end
    

    因此 朋友 可以有多个实例 Address 例如:

    Friend.last.addresses # office address, home address
    
    推荐文章