简体   繁体   中英

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?)

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.

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:

    location.category.parent_category

And given what you've outlined, I don't see the need for any polymorphic associations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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