Last active
May 18, 2021 09:01
-
-
Save thenapking/22b426704d8935a4fc451fe56407b620 to your computer and use it in GitHub Desktop.
Add Single Table Inheritance and a Tree Heirarchy to a model. See linked gist for an example of how to load data for a hierarchical table with STI https://gist.github.com/thenapking/3ccd4d20f3d9be74426ffa2354d44572
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models | |
class Location < ActiveRecord::Base | |
has_ancestry cache_depth: true, touch: true, orphan_strategy: :destroy | |
self.inheritance_column = :category | |
def self.categories | |
%w(World Country Division Region Area Store) | |
end | |
belongs_to :parent, class_name: "Location", foreign_key: "parent_id" | |
end | |
# For each location category create a file with an empty class, eg | |
class Store; end | |
# Now in the controllers use a variable called @klass to pick up the location category. | |
class LocationsController < ApplicationController | |
before_action :set_location_category #STI | |
def index | |
@locations = @klass.constantize.all | |
end | |
def show | |
@location = @klass.constantize.find(params[:location_id]) | |
end | |
private | |
def set_location_category | |
# if the location category is not recognised, make it a generic location. You could also log the issue | |
# this is only an issue if you are syncing this table from an external data source | |
@klass = Location.categories.include?(params[:category]) ? params[:category] : "Location" | |
end | |
end | |
# In your views you can make a dynamic heading based on the location's category | |
<h1><%= @klass.pluralize %></h1> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment