新手问题 如何建立一个所有页面都能访问的变量 @topics

w7938940 · 2012年08月28日 · 最后由 hlcfan 回复于 2012年08月29日 · 3105 次阅读

现在我要在一个网站的每个页面都显示数据库里最新文章的标题,最简单也是最笨的方法就是在每个 controller 的每个 action 下定义一个 @topics = Topic.order("created_at desc").limit(10) 然后在 application.html.erb 里来读取

<% @topic.each do |topic| %>
 <li>topic.title</li>
<% end %>

有没有最简单的方法来定义一个变量让所有的页面都能访问?

app/controllers/application_controller.rb

我觉得可以: 1、写在 application_helper.rb 中,用一个 helper 方法去做;

2、在 application_controller.rb 文件中初始化变量@topic。不妨试试。

#3 楼 @w7938940 比如在 application_helper.rb 文件中定义方法:

def top_topics
  Topic.order("created_at desc").limit(10)
end

在你的页面中就可以直接用 top_topics 了,在 application_controller.rb 中类似

这个最好是用 scope 啊

你的场景用 scope 会比较合适一些

#1 楼 @lidashuang 你好,我也刚好碰到这个问题,我在 application_controller 里写个方法,但是在 application.html.erb 中没有读出来,这个方法名有什么特殊吗?

#7 楼 @hlcfan 在 application_controller 里声明 helper_method :your_method_name

#8 楼 @fresh_fish 这不是和 application_helper 里写一样么?

#9 楼 @hlcfan 这样在 controller 和 views 里面都可以用

我看 lz 是想要一个@topics变量,

class ApplicationController < ActionController::Base before_filter :get_topics

private def get_topics @topics = Topic.order("created_at desc").limit(10) end

end

#7 楼 @hlcfan 在模板里要使其成为 helper_method

helper_method :current_user

#10 楼 @fresh_fish #12 楼 @lidashuang 怎么在 haml 里,这样的嵌套怎么写:

- @notifies.each do |n|
    %tr
        %td
            = getcomment n[1]             

这样写,n[1] 是错误的值

#15 楼 @hlcfan 贴完整的错误信息吧

#16 楼 @fresh_fish 可能我没说清楚,方法 getcomment 接到的参数并不是 n[1] 的值,而是'n[1]'

需要 登录 后方可回复, 如果你还没有账号请 注册新账号