我是Ruby on Rails的新手,我不確定使用Polymorphic Association。Address - Polymorphic association
我正在構建一個Yelp類似的應用程序。
我有一個用戶模型和一個場地模型。他們都有一個地址。是否使用多態關聯? (我不確定)
我是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
我不太確定你是否需要多形態。 首先想到的:你可以解決你的情況,如果你只是創建User
,Venue
和Address
模型,然後只寫用戶has_one :address
,地點has_one :address
和地址belongs_to :user
和belongs_to :venue
。
如果您希望Address
擁有User
或Venue
對象並將它們稱爲相似對象,則需要多態。我的意思是,你希望你的Address實體只有一個object
字段,它將在User
或Venue
上引用。
所以,如果你想這樣的電話: address.object.name
獲得,例如,用戶或地點的名稱以某種方式與該地址連接,你不介意閹這將是用戶或地點,你需要多態。如果您需要撥打電話address.user.name
和address.venue.name
,並且分隔屬於地址的場所和用戶很重要,則不需要多態。
希望,我很清楚莫名其妙... :)
下面是一個簡單的例子
*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
不錯! =) 地址模型之間的差異是緯度和經度列(在Venue模型中是必需的,而用戶模型不需要)。在這種情況下,最好的方法是什麼? – user1301037
在這種情況下,我必須創建一個列來引用用戶模型和其他場地模型? – user1301037
@ user1301037如果你的意思是,當你不需要多態時,那麼是的,你必須創建兩個參考列。但是這不是很正確:你必須看看你的結構,也許你應該使用'belongs_through'或者那樣的行爲來防止雙重和錯誤的結合。 – Ngoral