【发布时间】:2016-07-04 09:35:01
【问题描述】:
一个多星期以来,我一直在寻找解决问题的方法。我有一个作业,由于没有下一个/上一个功能,我失去了 10 分,而且时间用完了。不过我还是想弄清楚。
我用rails generate scaffold Ripple name:string message:text url:string 创建了一个简短的单页站点,它显示了 10 个最新帖子显示的索引(名称、消息、created_on、link_to“显示”)。我仍然必须创建下一个、上一个、最新、最旧的链接以显示下一个 10、上一个 10 .... 结果。我的代码。
app\controllers\ripple_controller.rb
class RipplesController < ApplicationController
before_action :set_ripple, only: [:show, :update]
before_action :restrict_destroy_edit, only: [:edit, :destroy]
before_filter :set_page
helper_method :link_name_to_url, :next_button, :previous_button, :newest_button, :oldest_button, :is_next_page_available, :is_previous_page_available
RIPPLES_PER_PAGE = 10
def index
@ripples = Ripple.order(:id).limit(RIPPLES_PER_PAGE).offset(@page * RIPPLES_PER_PAGE)
end
#All my show, new, destroy, edit, create ....
def next_button
end
def previous_button
end
def newest_button
end
def oldest_button
end
def is_next_page_available?
end
def is_previous_page_available?
end
def set_page
@page = 5
end
private
...
\app\views\ripples.html.erb
<table>
<thead>
<tr>
<th>Name</th>
<th>Message</th>
<th>Posted</th>
<th>Show Ripple</th>
</tr>
</thead>
<tbody>
<% @ripples.each do |ripple| %>
<tr>
<td><%= link_name_to_url ripple %></td>
<td><%= truncate(ripple.message, length: 50) %></td>
<td><%= ripple.created_at.strftime("%B %d, %Y %l:%M %P") %></td>
<td><%= button_to 'Show', ripple, :method => "get" %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<div id = "nav">
<button><%= link_to 'Newest' %></button>
<button><%= link_to 'Previous 10 Ripples' %></button>
<button><%= link_to "Next 10 Ripples" %></button>
<button><%= link_to 'Oldest' %></button>
<button><%= link_to 'New Ripple', new_ripple_path, class: "button", method: :get %></button>
</div>
我尝试在 Model 中调用方法,但在下一个和上一个时不断收到 undefined method "next" for #<Class:0xb4eabd0c> 错误。
app\models\ripple.rb
class Ripple < ActiveRecord::Base
default_scope -> {order(created_at: :desc)}
validates :name, :message, presence: true
validates :url, allow_blank: true, format: {
with: URI::regexp(%w(http https)),
message: "Must be a url starting with http:// or https://"
}
def next
Ripple.order(:id).limit(10).offset((@page - 1) * 10)
end
def previous
Ripple.order(:id).limit(10).offset((@page + 1) * 10)
end
end
我将如何使用 order().limit().offset 实现下一个和上一个,并可能使用@page 来跟踪我在 ActiveRecord 中的位置。也许像
def next_button
@page -= 1
end
无论哪种方式我都可以调用索引"<%= link_to Next 10" next_button %>,我没有可行的想法。
感谢您的帮助。
【问题讨论】:
-
你可以使用宝石吗?如果是这样,will_paginate 会为您做所有事情,如果不是,请查看它的源代码。
-
undefined method "next" for #<Class:0xb4eabd0c> error on next and previous你得到这个错误是因为你试图在课堂上打电话给instance method's。要使下一个和上一个方法在类级别可用,您需要在这些方法之前添加self。即def self.next和def self.previous -
我希望我能拥有,我知道如何使用 will-paginate。但是不,我必须自己写,虽然我今天确实得到了提示,使用 session[:page] 而不是 @page。显然 rails 不会在视图和控制器之间传递 ruby 变量。
标签: ruby-on-rails ruby ruby-on-rails-4 pagination