ActiveRecord方法最后不会带参数

时间:2014-01-20 21:35:59

标签: ruby-on-rails ruby activerecord

我试图在像这样的控制器中使用方法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/1KKK8epm

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

2 个答案:

答案 0 :(得分:1)

试试这个:

Post.order(:created_at).reverse_order.limit(2)

答案 1 :(得分:1)

添加上面的答案,如果你总是希望它是最后创建的两个条目,或者想要通过任何其他方法排序,你可以做类似的事情......

Post.order(:created_at).limit(2)