【发布时间】:2012-06-28 22:17:00
【问题描述】:
我正在尝试设置三个模型:位置/场地、类别和社区。p>
位置必须具有父类别和子类别,而其邻居是可选的。在 Category 模型中,有顶级类别或子类别。
鉴于上述情况,这是定义模型关联的正确方法吗?
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 Guide 之后,看起来多态关联可能更合适?)
【问题讨论】:
标签: ruby-on-rails model associations