0

我看到了一些类似的问题,但没有成功。我想在我的主页上显示 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>
4

3 回答 3

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

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

@posts = Post.order('created_at ASC').limit(3)
于 2013-07-08T17:48:34.040 回答
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

希望能帮助到你!

于 2013-07-08T20:54:30.523 回答
0

您的模型是“帖子”(不是帖子)吗?

这就是你如何使用 ActiveRecord 的限制。

def noticia
  @posts = Post.limit(3)
end
于 2013-07-08T20:41:54.480 回答