Rails: Dividing up a single database between multi

2019-04-11 19:03发布

问题:

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.