我有以下模型结构。 我有一个行程,有许多行程节点。每个行程节点都是地方,酒店,活动等的包装。例如。
行程=“巴黎之旅” Itinerary.itinerary_nodes = [Node1,Node2,Node3]在哪里 Node1 =“JFK机场” Node2 =“CDG机场” Node3 =“艾菲尔铁塔”
因此,节点基本上代表您将在行程中访问的地点。在我的模型结构中;我们假设我的机场模仿不同于纪念碑或酒店。现在我想创建一个关联,以便;
class ItineraryNode
include Mongoid::Document
has_one :stopover
end
每个中途停留可以是不同的对象。它的类型和id默认存储,稍后使用它进行充气。
那么如何声明多个模型与ItineraryMode相关联?我可以通过确保在初始化程序中手动设置这些属性来实现这一点;但是好奇,如果默认情况下支持这样的话。
干杯
答案 0 :(得分:4)
这不是“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
现在你可以得到:
@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
(我使用if
构造只是为了更好地展示多态性,你可以在这里使用case
构造......)
您看到node.stepover
可以是多个类。
编辑(在评论之后,我了解ItineraryNode
模型是针对多对多关联的手工制作多态的尝试。
来自Mongoid文档:
除has_and_belongs_to_many外,所有关系都允许使用Polymorhic行为。
所以你需要使用中间模型(ItineraryNode
)。提供的解决方案是我能想到的最简单的解决方案。