0

这是我第一次来这里。我是新来的铁路。我正在建立一个包含 PROJECTS 和 IMAGES 的站点,IMAGES 属于 PROJECTS。我有一个显示所有项目的列表操作,当我单击一个项目时,它会将我带到节目中。在节目中,我想在顶部添加 2 个链接,将我带到上一个和下一个项目。这是在我的 PROJECTS 模型中

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

这是在我的表演动作视图中

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

这是我在 ProjectController 中的表演动作

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

我正在使用 RAILS 4,在渲染显示视图时出现以下错误

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

我不知道我做错了什么。FIRST 和 WHERE 可以链接在一起吗?请教育我!!!!

4

1 回答 1

2

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

于 2013-08-21T18:27:33.923 回答