2012-05-23 59 views
1

我有一種情況,公司是由用戶管理的。即:用戶可以創建,閱讀,更新和刪除自己的公司。但我也希望同一用戶訪問系統中所有公司的列表,即使在註銷時也是如此。如何管理公共記錄和用戶特定記錄

如:

USER_A管理以下公司:company_a和company_b

USER_B管理以下公司:company_c和company_d

USER_A應該能夠看到他自己的公司名單(一和b)以及所有公司(a,b,c和d)的列表

在控制器中處理這個問題的最佳方法是什麼?

Idealy,我想有它安裝在2條獨立的路線如下:

/companies 
/users/1/companies 

我應該有公司,或者多一個控制器?這將如何工作?

我正在尋找這種情況下的最佳做法。

+0

可能的路由方法可以是: '資源:用戶 \t資源:公司 結束 匹配 '/企業'=> '公司#public_list':爲=>:public_companies_list' 所以,你可以使用一個UsersController和一次CompaniesController。 希望它有幫助! – thesis

+0

這實際上是我最喜歡的答案。 –

+0

檢查更新的答案。 – thesis

回答

0

恕我直言,如果所有用戶都可以看到所有的公司,那麼擁有一個控制器來完成這項工作是完美的。只需在模板中,您可以檢查當前用戶是否爲指定公司的作者,然後添加鏈接以編輯該公司等,如果您想要的話。

+0

雖然,我想向用戶展示兩個單獨的列表。一個僅適用於他們的公司,另一個適用於所有公司。我這樣做是因爲公司名單可能非常大。 –

+0

單頁上的兩個列表? – drupality

+0

有兩條獨立路線如下: /companies and/users/1/companies –

1

在您的情況的方法可以是:

  1. 使用Devise RubyGem來處理身份驗證。 https://github.com/plataformatec/devise
  2. 使用RESTful操作設置的簡單CompaniesController創建或腳手架:index, new, create, edit, udpate, destroy操作。
  3. CompaniesController添加before_filter訪問限制作用,這需要用戶的身份驗證:

    的before_filter:的authenticate_user!:除了=> [:public_list]

  4. 你應該有用戶和公司的ActiveRecord模型之間has_many assosiation ,訪問公司收集的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