Pacane
Pacane

Reputation: 21471

ActiveRecord method last won't take parameter

I'm trying to use the method last or even take in a controller like this

def news
    @posts = Post.last(2)
end

and when I go to the page I get the following error :

wrong number of arguments (1 for 0)

on the line

@posts = Post.last(2)

(and it does the same with Post.take(2))

However, it works when I do this:

@posts = Post.find(:all, :order => 'created_at DESC', :limit => 2)

but warns me about the fact that this method is deprecated.

Here's the code of my view:

<% @posts.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= post.text %></td>
  </tr>
<% end %>

I'm using Ruby 2 and Rails 4

Person.last(3) # returns the last three objects fetched by SELECT * FROM people.

as stated here : http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-last

edit:

Here's the full controller and the full stacktrace : 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

Upvotes: 1

Views: 224

Answers (2)

Agis
Agis

Reputation: 33626

Try this:

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

Upvotes: 1

frenchloaf
frenchloaf

Reputation: 1054

Adding on to the answer above, if you always want it to be the last two entries created, or want to sort by any other method, you can do something like...

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

Upvotes: 1

Related Questions