我看到了一些类似的问题,但没有成功。 我想在我的主页上显示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 :(得分: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 :(得分: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
希望它有所帮助!
答案 2 :(得分:0)
你的模特'发布'(不是帖子)?
这就是你对ActiveRecord使用限制的方式。
def noticia
@posts = Post.limit(3)
end