我正在尝试在像这样的控制器中使用方法last
甚至take
def news
@posts = Post.last(2)
end
当我进入页面时,我会收到以下错误:
wrong number of arguments (1 for 0)
在线上
@posts = Post.last(2)
(并且与Post.take(2)
进行相同的操作)
但是,当我这样做时,它有效:
@posts = Post.find(:all, :order => 'created_at DESC', :limit => 2)
,但警告我说这种方法被弃用了。
这是我观点的代码:
<% @posts.each do |post| %>
<tr>
<td><%= post.title %></td>
<td><%= post.text %></td>
</tr>
<% end %>
我正在使用Ruby 2和Rails 4
Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
如下所述:http://api.rubyonrails.org/classes/activerecord/findermethods.html#method-i-last
编辑:
这是完整的控制器和完整的堆栈:http://pastebin.com/1kkkk8epm:
class PostsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show, :news]
load_and_authorize_resource
rescue_from CanCan::AccessDenied do |exception|
redirect_to posts_path, :alert => exception.message
end
def index
@posts = Post.all
end
def news
#@posts = Post.order(:created_at).reverse_order.limit(2)
@posts = Post.last(2)
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to action: :show, id: @post.id
else
render 'edit'
end
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to action: :show, id: @post.id
else
render 'new'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to action: :index
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
添加到上面的答案中,如果您始终希望它是创建的最后两个条目,或者想通过任何其他方法进行排序,则可以做类似...
Post.order(:created_at).limit(2)
尝试以下:
Post.order(:created_at).reverse_order.limit(2)