[英]Inverse of Mongoid has_one polymorphic association
I have a following model structure. 我有以下模型结构。 I have an Itinerary that has many itinerary nodes. 我有一个包含许多行程节点的行程。 Each itinerary node is a wrapper around either a place, hotel, activity etc. So for example. 每个行程节点都是围绕地点,酒店,活动等的包装。因此,例如。
Itinerary = "Trip to Paris" Itinerary.itinerary_nodes = [Node1, Node2, Node3] where Node1 = "JFK Airport" Node2 = "CDG Airport" Node3 = "Eiffel Tower" 行程=“巴黎之行” Itinerary.itinerary_nodes = [Node1,Node2,Node3],其中Node1 =“肯尼迪国际机场” Node2 =“ CDG机场” Node3 =“艾菲尔铁塔”
So essentially nodes represents the places you will visit in your itinerary. 因此,本质上,节点代表了您将在行程中访问的地方。 In my model structure; 在我的模型结构中; lets assume that my airports are modeled different from monuments or hotels. 假设我的机场的建模方式不同于古迹或酒店。 Now I want to create a association such that; 现在,我想创建一个这样的关联:
class ItineraryNode
include Mongoid::Document
has_one :stopover
end
Where each stopover can be a different object. 每个停留点可以是一个不同的对象。 It's type and id is stored by default and is later inflated using that. 它的类型和ID默认情况下会存储,然后使用它进行膨胀。
So how do I declare multiple models to be associated to ItineraryMode? 那么,如何声明多个模型与ItineraryMode相关联? I can implement this specifically by ensuring that I set these attributes manually in initializer; 我可以通过确保在初始化程序中手动设置这些属性来实现此目的。 but curious if something like this is supported by default. 但很好奇默认情况下是否支持这种方式。
Cheers 干杯
This is not a "has_one", it is a "belongs_to" (polymorphic) 这不是“ has_one”,而是“ belongs_to”(多态)
class ItineraryNode
include Mongoid::Document
belongs_to :stopover, :polymorphic => true
belongs_to :itinerary
end
class Airport
include Mongoid::Document
has_many :itinerary_nodes, :as => :stopover
end
class Place
include Mongoid::Document
has_many :itinerary_nodes, :as => :stopover
end
So now you can get: 现在,您可以获得:
@itinerary.itinerary_nodes.each do |node|
if node.stopover.is_a? Airport
puts "Welcome to #{note.stopover.name}"
elsif node.stopover.is_a? Event
puts "Bienvenue, would you like a drink?"
elsif node.stepover.is_a? Place
puts "The ticket line is over there"
end
end
(I used an if
construct just to show better the polymorphism, you would use a case
construct here...) (我使用了if
构造只是为了更好地显示多态性,您可以在这里使用case
构造...)
You see that node.stepover
can be of many classes. 您会看到node.stepover
可以属于许多类。
EDIT (after the comment, I understand that the ItineraryNode
model is an attempt to a handcrafted polymorphism for a many-to-many association. 编辑 (在评论后,我了解到ItineraryNode
模型是针对多对多关联的手工多态性的尝试。
From the Mongoid documentation: 从Mongoid文档中:
Polymorhic behavior is allowed on all relations with the exception of has_and_belongs_to_many. 除has_and_belongs_to_many之外,所有关系都允许多态行为。
So you need to use an intermediate model ( ItineraryNode
). 因此,您需要使用中间模型( ItineraryNode
)。 The provided solution is the simplest one I can think of. 提供的解决方案是我能想到的最简单的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.