显示视图中的“上一篇文章”和“下一篇文章”链接(嵌套资源)

时间:2013-10-19 21:35:19

标签: ruby-on-rails ruby nested-resources

在我的应用程序中,我想在文章显示视图的底部添加“上一篇文章”和“下一篇文章”链接。

这是我到目前为止所得到的但我得到了这个错误:

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

我知道路径必须如此(但我很难实现它)

myapp/users/1/article/1 

铁路新手请帮忙......

路线

resources users do
  resources articles
end

模型

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

视图

文章显示页面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 个答案:

答案 0 :(得分:2)

只需使用

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

以类比方式休息。