“Previous post” and “Next post” link in Show View

2019-04-01 18:16发布

问题:

In my Application I want to add a "Previous Article" and a "Next Article" link in the bottom of my Article Show View.

This is what I have so far but I get this error:

undefined method `article_path' for #<#<Class:0x007fd7c581af48>:0x007fd7cb8e5968>

I know the path must look like this (but i am having a hard time implementing it)

myapp/users/1/article/1 

New to Rail Please Help ...

ROUTES

resources users do
  resources articles
end

MODELS

class User < ActiveRecord::Base
 attr_accessible :name, :photo

 has_many :articles

end

class Article < ActiveRecord::Base
  attr_accessible :name

  belongs_to :user

  def next
    user.articles.where("id > ?", id).order("id ASC").first
  end

  def prev
    user.articles.where("id < ?", id).order("id DESC").first
  end

end

VIEWS

Articles Show Page appname/users/1/articles/1

<%= link_to @article.name %>

<%= link_to "next", @article.next %>
<%= link_to "previous", @article.prev %>

CONTROLLER

class ArticlesController < ApplicationController

  before_filter :get_publisher

  def get_user
    @user = User.find(params[:user_id])
  end

  def show
    @article = @user.articles.find(params[:id])
  end

  def index
    @articles = @user.articles
  end

end

回答1:

Simply use

<%= link_to 'next', user_article_path(@user, @article.next) %>

And rest by analogy.