地址 - 多态协会

时间:2016-09-06 22:34:36

标签: ruby-on-rails polymorphic-associations

我在Ruby on Rails上很新,而且我不确定使用多态协会。

我正在构建类似Yelp的应用程序。

我有一个User模型和Venue模型。他们俩都有一个地址。是否使用多态关联? (我不确定)

3 个答案:

答案 0 :(得分:1)

这将是利用多态关联的情况,以下是基于您所描述的内容的示例。

class User
  has_one :address, as: :addressable
end

class Venue
  has_one :address, as: :addressable
end

class Address
  belongs_to :addressable, polymorphic: true
end

答案 1 :(得分:1)

我不太确定你是否需要多态。 首先考虑一下:如果您只是创建UserVenueAddress模型然后只写那个用户has_one :address,地点has_one :address和地址,您能否解决问题? belongs_to :userbelongs_to :venue

如果您希望Address拥有UserVenue对象并将其称为类似对象,那么您需要具有多态性。我的意思是,您希望您的地址实体只有一个object字段,该字段将在UserVenue上引用。

所以,如果你想这样打电话: 例如,address.object.name可以获得与此地址有某种联系的用户或地点的名称,而您不介意,这将是用户或地点,您需要多态。如果您需要address.user.nameaddress.venue.name之类的通话,并且将地址与属于地址的用户分开是很重要的,那么您就不需要多态。

希望,我以某种方式清楚......:)

答案 2 :(得分:0)

这是一个简单的例子

*In student.rb file*
 class Student < ActiveRecord::Base
  has_one :profile, as: :profileable, dependent: :destroy
end

*In teacher.rb file*
class Teacher < ActiveRecord::Base
  has_one :profile, as: :profileable, dependent: :destroy
end

*In profile.rb file*
class Profile < ActiveRecord::Base
  belongs_to :profileable, polymorphic: true
end

通过

获取学生详细信息
@student_detail = @student.profile.detail  

通过

获取教师详细信息
 @teacher_detail = @teacher.profile.detail