2013-08-27 130 views
0

的Ruby 1.9.3 + Rails的3.2.8模型訪問

我有一個是在每一頁上呈現在我的應用程序內部的局部視圖:

<span id="sync-time">  
    <%= @sync.dropbox_last_sync.strftime('%b %e, %Y at %H:%M') %> 
</span> 

爲了要使用我的syncs模型,並有權訪問dropbox_last_sync方法,我必須將其包含在中,每個控制器貫穿我的應用程序。例如:

class EntriesController < ApplicationController 
    def index 
    @sync = current_user.sync 
    end 
end 

...

class CurrenciesController < ApplicationController 
    def index 
    @sync = current_user.sync 
    end 
end 

...等。

有沒有一種辦法可以讓現有的syncs模型處處包括它在我的應用程序控制器不知何故?

回答

2

你應該能夠在你的應用程序控制器添加的before_filter:

before_filter :setup_sync 

def setup_sync 
    if current_user 
    @sync = current_user.sync 
    end 
end 

你要小心,你的setup_sync過濾器的任何代碼使用的是設置你的CURRENT_USER後運行。這可能是另一個before_filter,雖然如此規定你有before_filter :setup_sync宣佈你目前的用戶過濾它會正常工作。

+0

很好,謝謝! –

0

這是更好的:

class ApplicationController < ActionController::Base 
    before_filter :authenciate_user! 
    before_filter :index 

    def index 
    @sync = current_user.sync 
    end 
end 

您使用current_user始終,所以你需要有before_filter :authenciate_user!這裏藏漢及以上的其他一個。