我的情况是公司由用户管理。即:用户可以创建,阅读,更新和删除自己的公司。但我也希望同一个用户访问系统中所有公司的列表,即使在注销时也是如此。
例如:
user_a管理以下公司:company_a和company_b
user_b管理以下公司:company_c和company_d
user_a应该能够看到他自己公司的列表(a和b)以及所有公司的列表(a,b,c和d)
在控制器中处理此问题的最佳方法是什么?
理想情况下,我想在两条不同的路线下设置如下:
/companies
/users/1/companies
我应该为公司设置一个控制器,还是多个?那怎么会有用呢?
我正在寻找这种情况下的最佳做法。
答案 0 :(得分:1)
在您的情况下,方法可以是:
Devise
RubyGem来处理身份验证。 https://github.com/plataformatec/devise index, new, create, edit, udpate, destroy
actions。在before_filter
中添加CompaniesController
以限制对需要用户身份验证的操作的访问权限:
before_filter:authenticate_user!,:except => [:public_list]
has_many
协商,以访问current_user
的公司集合。以下是示例代码:
路由:
resources :users do
resources :companies
end
match '/companies' => 'companies#public_list', :as => :public_companies_list
控制器:
class CompaniesController < ApplicationController
before_filter :authenticate_user!, :except => [:public_list]
def index
@companies = current_user.companies
end
def show
@company = current_user.companies.find(params[:id])
end
def new
@company = current_user.companies.new
end
def edit
@company = current_user.companies.find(params[:id])
end
def create
@company = current_user.companies.new(params[:company])
respond_to do |format|
if @company.save
format.html { redirect_to @company, notice: 'Company was successfully created.' }
else
format.html { render action: "new" }
end
end
end
def update
@company = current_user.companies.find(params[:id])
respond_to do |format|
if @company.update_attributes(params[:company])
format.html { redirect_to @company, notice: 'Company was successfully updated.' }
else
format.html { render action: "edit" }
end
end
end
def destroy
@company = current_user.companies.find(params[:id])
@company.destroy
respond_to do |format|
format.html { redirect_to companies_url }
end
end
end
对于上市公司列表,添加此方法:
def public_list
@companies = Company.all
end
答案 1 :(得分:0)
恕我直言,如果所有用户都能看到所有公司,那么拥有一台控制器来完成这项工作是完美的。只需在模板中,您可以检查当前用户是否是指定公司的作者,然后添加链接以编辑该公司等。