Address - Polymorphic association

问题描述:

我是Ruby on Rails的新手,我不确定使用Polymorphic Association。Address - Polymorphic association

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

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

这将是一个利用多态关联的情况,下面是一个基于你所描述的例子。

class User 
    has_one :address, as: :addressable 
end 

class Venue 
    has_one :address, as: :addressable 
end 

class Address 
    belongs_to :addressable, polymorphic: true 
end 

我不太确定你是否需要多形态。 首先想到的:你可以解决你的情况,如果你只是创建UserVenueAddress模型,然后只写用户has_one :address,地点has_one :address和地址belongs_to :userbelongs_to :venue

如果您希望Address拥有UserVenue对象并将它们称为相似对象,则需要多态。我的意思是,你希望你的Address实体只有一个object字段,它将在UserVenue上引用。

所以,如果你想这样的电话: address.object.name获得,例如,用户或地点的名称以某种方式与该地址连接,你不介意阉这将是用户或地点,你需要多态。如果您需要拨打电话address.user.nameaddress.venue.name,并且分隔属于地址的场所和用户很重要,则不需要多态。

希望,我很清楚莫名其妙... :)

+0

在这种情况下,我必须创建一个列来引用用户模型和其他场地模型? – user1301037

+0

@ user1301037如果你的意思是,当你不需要多态时,那么是的,你必须创建两个参考列。但是这不是很正确:你必须看看你的结构,也许你应该使用'belongs_through'或者那样的行为来防止双重和错误的结合。 – Ngoral

下面是一个简单的例子

*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 
+0

不错! =) 地址模型之间的差异是纬度和经度列(在Venue模型中是必需的,而用户模型不需要)。在这种情况下,最好的方法是什么? – user1301037