Skip to content

Instantly share code, notes, and snippets.

@novohispano
Created May 18, 2015 07:34
Show Gist options
  • Save novohispano/166b3d79d26af9d94abc to your computer and use it in GitHub Desktop.
Save novohispano/166b3d79d26af9d94abc to your computer and use it in GitHub Desktop.
Multitenant Storedom
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Storedom</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<% if @current_store %>
<li>
<%= link_to 'Items', store_items_path %>
</li>
<li>
<%= link_to 'Orders', store_orders_path %>
</li>
<% end %>
</ul>
</div>
</nav>
class Item < ActiveRecord::Base
has_many :order_items
has_many :orders, through: :order_items
belongs_to :store
end
class Stores::ItemsController < Stores::StoresController
def index
@items = current_store.items
end
end
class Stores::OrdersController < Stores::StoresController
def index
@orders = current_store.orders
end
end
<div class="container">
<h1>Welcome to <%= current_store.name %></h1>
<% @orders.each do |order| %>
<div class="col-sm-12">
<h2>Order <%= order.id %></h2>
<h5>Client: <%= order.user.name %></h5>
<h5>Order Items</h5>
<% order.items.each_with_index do |item, index| %>
<p>
<%= "#{index + 1}. #{item.name}" %>
</p>
<% end %>
</div>
<% end %>
</div>
Rails.application.routes.draw do
resources :items, only: [:index, :show]
resources :orders, only: [:index, :show]
resources :users, only: [:index, :show]
namespace :stores, path: ':store', as: :store do
resources :items, only: [:index, :show]
resources :orders, only: [:index, :show]
end
root 'stores#index'
end
class Store < ActiveRecord::Base
has_many :items
has_many :orders
validates :url, uniqueness: true, presence: true
validates :name, presence: true
before_validation :generate_url
def generate_url
self.url = name.parameterize
end
end
class StoresController < ApplicationController
def index
@stores = Store.all
end
end
class Stores::StoresController < ApplicationController
before_action :store_not_found
helper_method :current_store
def current_store
@current_store ||= Store.find_by(url: params[:store])
end
def store_not_found
redirect_to root_path unless current_store
end
end
<div class="container">
<h1>Welcome to <%= current_store.name %></h1>
<% @items.each do |item| %>
<div class="col-sm-3">
<h5><%= item.name %></h5>
<%= link_to(image_tag(item.image_url), item_path(item)) %>
<p>
<%= item.description %>
</p>
</div>
<% end %>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment