Juan Delgado
Juan Delgado

Reputation: 3

creating next/previous links rails 4

This is my first time here. I'm new to rails. I'm building a site that has PROJECTS and IMAGES, IMAGES belongs to PROJECTS. I have a list action that shows all PROJECTS and when I click a project it takes me to the show. In the show I want to add 2 links at the top that take me to the previous and next PROJECTS. This is in my PROJECTS model

has_many :images
accepts_nested_attributes_for :images, allow_destroy: true
scope :sorted, order(id: :asc)
def previous
Project.first.where("projects.id > ?", :id).order(id: :desc)
end

def next
Project.first.where("projects.id < ?", :id).order(id: :asc)
end

This is in my show action view

=link_to('<< Previous',{:id => @project.previous})
=link_to('Next >>',{:id => @project.next})

This is my show action in ProjectController

def show
@project = Project.find(params[:id])
end

I am using RAILS 4 and I get the following error when rendering the show view

undefined method `where' for #<Project:0x007fadbcc66878>

I don't know what I'm doing wrong. Can FIRST and WHERE be chained together? Please educate me !!!!

Upvotes: 0

Views: 1230

Answers (1)

Zippie
Zippie

Reputation: 6088

You can use it like this:

Project.where("projects.id > ?", :id).order(id: :desc).first

What you were trying to do was chaining the where method on a Project object, instead on a ActiveRecord::Relation object ('list' of Project objects)

Hows about another solution:

def show   
    @project = Project.find(params[:id])   
    @previous = Project.where("id < ?", params[:id]).order(:id).first   
    @next = Project.where("id > ?", params[:id]).order(:id).first 
end

And then in your view just see if @previous and @next are present (they can be nil if its the first or last project) and render the link/button such as:

if @previous
  link_to "Previous", @previous

This way you don't need any other actions such as previous and next

Upvotes: 2

Related Questions