2015-04-18 29 views
0

我想,以確保下面的方法軌道4:往哪裏放了爲所有控制器

  def current_user 
       current_user = current_member 
      end 

是提供給我的所有控制器 我試圖把它的所有操作所需的功能ApplicationsController沒有運氣。

我試圖在以下

Where to put Ruby helper methods for Rails controllers?

由於沒有效果使用的解決方案。

這是什麼Rails方式的解決方案?

我在我的ApplicationsHelper中有相同的方法,我可以在我的視圖中訪問它沒有問題。

編輯:

給予更多的細節。 我有一個應用程序與我從頭構建的身份驗證系統,這使用SessionHelper文件中稱爲「current_user」的函數

我一直在將Devise實現到我的應用程序中,並維護我的用戶模型以保存用戶詳細信息,但創建了一個成員模型來保存設計認證信息(即保持用戶配置文件信息與表格設計分開使用,正如文檔所建議的那樣)。

這給了我一個名爲current_member的設計幫助方法(基於我對模型的命名)。

我有「current_user」遍佈我的應用程序,無論是在控制器操作和視圖。

我想創建一個將current_member別名爲current_user的應用程序範圍的幫助器。嚴格地說,在我的問題中,我的函數是錯誤的 - 這會將current_user分配給成員類的實例。由於成員和用戶之間存在一對一關係,外鍵爲member.id,因此正確的功能是......

def current_user if member_signed_in? CURRENT_USER = User.find_by_member_id(current_member.id) 結束 結束

我ApplicationHelper:

module ApplicationHelper 


    def current_user 
     if member_signed_in? 
     current_user = User.find_by_member_id(current_member.id) 
     end 
    end 
    end 

該負責CURRENT_USER在各方面的意見, 但我不能讓它工作在控制器......看到例如這些代碼的UserController中

def show 
    @associates = [] 
    @colleagues = current_user.nearbys(1000).take(20) 
    @colleagues.each do |associate| 
     unless current_user.following?(associate) || current_user == associate 
     @associates.push(associate) 
    end 
    end 
    impressionist(@user) 
end 

我「秀」行動忘記我只是用地理編碼近找到用戶邏輯值。它的current_user解析爲「無」。

即使我把

before_action :current_user 

    def current_user 
     if member_signed_in? 
     current_user = User.find_by_member_id(current_member.id) 
     end 
    end 

在UserController中,CURRENT_USER沒有行動中工作。我在其他控制器的action中也有current_user,並且應用在這些點處中斷,但當current_user處於視圖中時不會。

讓我知道你是否需要更多信息。

編輯2:

我加

before_action :authenticate_member! 

到UsersController,但仍然沒有效果。編輯3:

我是個白癡。在零級錯誤發生在,因爲我在數據庫中沒有種子數據,因此

 @colleagues = current_user.nearbys(1000).take(20) 

@colleagues是零,因此呼籲「採取」零上被拋出一個錯誤。 新人的錯誤。

回答

0

當您定義應用程序操作時,如果您希望它們跨所有其他操作可用,則需要設置before過濾器。因此,在您的應用程序控制器,你會碰到這樣的:

before_action :current_user 

def current_user 
    current_user = current_member 
end 

這將在應用程序中運行任何其他行動之前,這個動作無論控制器

+0

不幸的是這只是崩潰 - 一個500錯誤 – GhostRider

+0

可以顯示任何你的代碼?沒有看到您的代碼或錯誤,很難找出錯誤是什麼... – abbott567

0

我覺得有你的問題的兩個部分。

1 - 哪裏可以放置所有控制器所需的功能?

所以一般的回答是把他們在ApplicationController,因爲通常所有其他控制器從ApplicationController

2繼承 - 關於你所得到的錯誤。

我的猜測是,在調用devise方法之前,您尚未加載devise。因此,嘗試像

class ApplicationController < ActionController::Base 
    before_action :authenticate_member! 
    before_action :current_user 

    def current_user 
    #your method 
    end 
end 

,並作爲一個建議,因爲你正在使用的助手同樣的方法,讓事情變得乾燥,可以使控制器方法的輔助方法。因此,將可跨越的意見

class ApplicationController < ActionController::Base 
    helper_method :current_user 
    before_action :authenticate_member! 
    before_action :current_user 

    def current_user 
    #your method 
    end 
end 

所以在你看來,你可以使用current_user

如果所有的失敗,因爲@ abbott567說發表您的錯誤日誌。

HTH