简体   繁体   English

如何为该架构建模Rails关联

[英]How to model Rails associations for this schema

I have three models that I'm trying to setup: Location/Venues, Categories, and Neighborhoods. 我尝试设置三种模型:位置/地点,类别和邻域。

A Location must have a parent Category and sub-Category, whereas its Neighborhood is optional. 位置必须具有父类别和子类别,而其邻居是可选的。 In the Category model, there's either top-level categories or subcategories. 在“类别”模型中,有顶级类别或子类别。

Given the above, is this the correct way to define the model associations? 鉴于以上所述,这是定义模型关联的正确方法吗?

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

(Actually, after reading more of the appropriate Rails Guide , it looks like polymorphic associations might be more appropriate instead?) (实际上,在阅读了更多适当的《 Rails指南》之后 ,看起来多态关联可能更合适吗?)

It somewhat depends on how you'd like your relationship of Locations and Categories to work; 这在某种程度上取决于您希望位置和类别之间的关系如何工作。 but if you're saying a Location must belong to a subcategory and category, it seems like you mean that a Location must simply belong to a subcategory (which has a category). 但是如果您说一个位置必须属于一个子类别类别,则似乎意味着一个位置必须简单地属于一个子类别(具有一个类别)。 So I think your associations are correct except the "parent_category" on Location is redundant. 因此,我认为您的关联是正确的,只是Location上的“ parent_category”是多余的。

For example, let's say I had the following: 例如,假设我有以下内容:

    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}

Now I have a location with a category of "Rock", and I could figure out it's parent category ("Music") like so: 现在,我有一个类别为“ Rock”的位置,可以像这样找出其父类别(“ Music”):

    location.category.parent_category

And given what you've outlined, I don't see the need for any polymorphic associations. 考虑到您所概述的内容,我认为不需要任何多态关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM