Active Record获得具有多态关系的关联模型

时间:2018-04-24 05:18:05

标签: ruby-on-rails ruby activerecord polymorphism

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

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 个答案:

答案 0 :(得分:1)

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,因此您没有地址的朋友列表,您有朋友的地址列表。

答案 1 :(得分:1)

正如您定义的多态模型。

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

一个地址将与UserFriend 的一个实例相关联。

请参阅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

因此Friend的每个实例都可以有Address的多个实例,如:

Friend.last.addresses # office address, home address
相关问题