2013-08-27 127 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!这里藏汉及以上的其他一个。