Rails: Dividing up a single database between multiple subdomains

天涯浪子 提交于 2019-12-06 07:56:59

问题


I'm relatively new to Rails, and here is my situation:

I'm building an inventory management app with rails to help three separate branches of a company manage their own product inventory.

Each of these three branches are keeping track of the same products, use the same data models, but are managed separately. My plan is to build a single app using a single database, but one that keeps track of the inventory in all three branches.

My plan is to have something like this:

branch1.inventoryapp.com

branch2.inventoryapp.com

branch3.inventoryapp.com

Each subdomain will lead to the same interface with the same functions and essentially the same views. The only difference will be the actual content of their inventory, which will be a list of products that are physically at that branch at the time.

Will I be able to do this with rails subdomain routing?

Should I have separate controllers for each branch?

Should I use controller namespaces? Nested resources?

Thanks in advance!


回答1:


In your application_controller, simply:

class ApplicationController < ActionController::Base
  before_filter :current_account
  helper_method :current_account

  def current_account
    @account ||= Account.find_by_domain(request.subdomain)
  end
end

Then, everywhere else:

class WidgetsController < ApplicationController

  def index
    @widgets = current_account.widgets.paginate(:page=>params[:page])
  end

  def show
    @widget = current_account.widgets.find(params[:id])
  end

  def create
    @widget = current_account.widgets.build(params[:widget])
    if @widget.save
      ...
    end
  end
end

By scoping everything to @account, you are keeping data separate across the subdomains.

You can also use current_account as a helper in your views.



来源:https://stackoverflow.com/questions/6541576/rails-dividing-up-a-single-database-between-multiple-subdomains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!