我正在尝试创建下一个按钮,每个页面只显示一条记录。我知道我们可以使用分页但我只想拥有下一个按钮。所以,我阅读了以下帖子并实现了它: 我的问题控制器:
class QuestionsController < ApplicationController
before_action :set_page, only: [:view]
QUESTIONS_PER_PAGE = 1
def view
questions=[]
@evaluation = Evaluation.pluck(:content).last
@evaluation.each do |question|
questions << question
end
@questions=Question.where(:content => questions).limit(QUESTIONS_PER_PAGE).offset(@page*QUESTIONS_PER_PAGE)
#@questions=Question.where(:content => questions).paginate(page: params[:page],per_page: 1)
end
private
def set_page
@page = params[:page] || 0
end
我的view.html.erb ,它给出了错误:没有将Integer隐式转换为String
<h1>Self-Evaluation Exam</h1>
<table id="questions">
<thead>
<tr>
<th>Content </th>
</tr>
</thead>
<tbody>
<% @questions.each do |question| %>
<tr>
<td><%= question.content %></td>
<td><%= check_box_tag question.c1 %></td>
<td><%= question.c1%></td>
<td><%= check_box_tag question.c2 %></td>
<td><%= question.c2%></td>
<td><%= check_box_tag question.c3 %></td>
<td><%= question.c3%></td>
<td><%= check_box_tag question.c4 %></td>
<td><%= question.c4%></td>
<td><%= check_box_tag question.c5 %></td>
<td><%= question.c5%></td>
</tr>
<% end %>
</tbody>
</table>
<div id = "nav">
<%= button_to 'Next',questions_path(page: @page + 1) %># this line gives error: no implicit conversion of Integer into String
</div>
<li><%= link_to 'Personal Evaluation',instructions_student_path %></li>
Paginate without a gem Next, Previous, buttons for Name.order(:id).limit(10).offset(0) 它显示了第一页,但是当我点击按钮时,我得到了错误 PS:下一个按钮应该在最后一条记录上改为提交 谢谢
答案 0 :(得分:0)
错误告诉您网址构建器失败,因为它尝试将整数转换为字符串。此外,递增值通常为+ =。
我打赌params [:page]返回的是字符串而不是整数。如果你@page.to_i += 1
会怎么样?沿着这些方向的东西至少会让你超越这个初始错误。
答案 1 :(得分:0)
非常简单,请尝试以下
QUESTIONS_PER_PAGE = 1
@questions = Question.where(content: questions).offset(QUESTIONS_PER_PAGE * @page).limit(QUESTIONS_PER_PAGE)
private
def set_page
@page = (params[:page] || 0).to_i
end
使用view.html.erb
和next >>
<< previous
<div id="nav">
<nav>
<ul class="pager">
<li class="previous <%= @page == 0 ? 'disabled' : '' %>">
<%= link_to_if page > 0, "← Previous".html_safe, questions_path(page: @page - 1) %>
</li>
<li class="next">
<%= link_to "Next →".html_safe, questions_path(page: @page + 1) %>
</li>
</ul>
</nav>
</div>
所以你的controller
看起来像这样
class QuestionsController < ApplicationController
before_action :set_page, only: [:view]
QUESTIONS_PER_PAGE = 1
def view
questions=[]
@evaluation = Evaluation.pluck(:content).last
@evaluation.each do |question|
questions << question
end
@questions = Question.where(content: questions).offset(QUESTIONS_PER_PAGE * @page).limit(QUESTIONS_PER_PAGE)
end
private
def set_page
@page = (params[:page] || 0).to_i
end
end
如果您只需要查看下一个按钮,则只能使用
<%= link_to "Next →".html_safe, questions_path(page: @page + 1) %>
有条件
<% if @page == @questions.count %>
<button>Finished</button>
<% else %>
<%= link_to "Next →".html_safe, questions_path(page: @page + 1) %>
<% end %>