[英]How to model Rails associations for this schema
我尝试设置三种模型:位置/地点,类别和邻域。
位置必须具有父类别和子类别,而其邻居是可选的。 在“类别”模型中,有顶级类别或子类别。
鉴于以上所述,这是定义模型关联的正确方法吗?
class Location < ActiveRecord::Base
attr_accessible # location-specific columns
belongs_to :category
belongs_to :parent_category, :class_name => "Category"
belongs_to :neighborhood
end
class Category < ActiveRecord::Base
has_many :locations
has_many :subcategories, :class_name => "Category", :foreign_key => "parent_category_id"
belongs_to :parent_category, :class_name => "Category"
end
class Neighborhood < ActiveRecord::Base
has_many :locations
end
(实际上,在阅读了更多适当的《 Rails指南》之后 ,看起来多态关联可能更合适吗?)
这在某种程度上取决于您希望位置和类别之间的关系如何工作。 但是如果您说一个位置必须属于一个子类别和类别,则似乎意味着一个位置必须简单地属于一个子类别(具有一个类别)。 因此,我认为您的关联是正确的,只是Location上的“ parent_category”是多余的。
例如,假设我有以下内容:
music = Category.create {title: 'Music'}
rock = Category.create {title: 'Rock', parent_category_id: music.id}
location = Location.create {title: 'The Fillmore', category_id: rock.id}
现在,我有一个类别为“ Rock”的位置,可以像这样找出其父类别(“ Music”):
location.category.parent_category
考虑到您所概述的内容,我认为不需要任何多态关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.