“Previous post” and “Next post” link in Show View (Nested Resources)

岁酱吖の 提交于 2019-12-21 06:06:40

问题


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.



来源:https://stackoverflow.com/questions/19471430/previous-post-and-next-post-link-in-show-view-nested-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!