2013-07-08 81 views
0

我看到了一些類似的問題,但沒有成功。 我想在我的主頁上顯示3條最新帖子。在主頁欄目上顯示3條最新帖子

我定義我的PostsController

def noticia 
    @posts = Posts.all(:limit => 3) 
    end 
    helper_method :noticia 

這種方法,我調用這個對我的看法

- if @noticia 
    %h4.feed 
    A Sair 
    %h6 
     %span= @noticia.created_at.strftime("%d %b. %Y") 
     = link_to @noticia.content, posts_path 
    %p 
     - if current_admin 
     = link_to "Adicionar notícia", new_post_path 

它給NoMethodError

undefined method `each' for #<Post:0x00000102fb6fc8> 
+0

默認範圍是否有限制? – Swards

+0

您是否在您的視圖中引用@posts? – Swards

回答

2

代碼中有很多奇怪的事情。

noticia方法應該是:

def noticia 
    @posts = Post.order("created_at desc").limit(3) 
end 

你並不需要使用helper_method

而且你的視圖文件必須是這樣的:

- if @posts.any? 
    - @posts.each do |post| 
    = # do something with my post 

希望它能幫助!

+0

謝謝,它有幫助! – kinguerra

2
@posts = Post.order('created_at').limit(3) 

@posts = Post.order('created_at DESC').limit(3) 

@posts = Post.order('created_at ASC').limit(3) 
+1

我已經在我的Post模型上設置了default_scope。問題是我不能調用最新的3個元素 – kinguerra

+1

這是行不通的。 =>'undefined method'order'for#'。您必須刪除對「全部」方法的調用。 –

+0

@JohnMcKey謝謝你的領導。我更新了代碼示例。 – westonplatter

0

是型號「後'(不是帖子)?

這是你如何使用ActiveRecord的限制。

def noticia 
    @posts = Post.limit(3) 
end 
相關問題