我有课和字的模型,在那里,一节课有很多单词。在每个课程视图中,用户可以访问属于该课程的单词的显示视图。
我已经为我的显示视图实现了“以前”和“下一步”链接,遵循了this post的想法。然而,课程的第一个单词显示了一个“前一个”链接,它链接到另一个课程的最后一个单词;一个课程的最后一个单词类似地链接到另一个课程的第一个单词(唯一的例外是数据库的第一个和非常最后的单词)。如何将上/下一次链接仅限于属于当前课程的单词?
Word模型:
class Word < ActiveRecord::Base
belongs_to :lesson
def previous
Word.where(["id < ?", id]).last
end
def next
Word.where(["id > ?", id]).first
end
end
文字显示视图:
<div class="col-xs-10 col-xs-offset-1">
<h1 class="text-center"><%= current_word.term %></h1><br>
<%= image_tag(current_word.image, class: 'img-responsive') %><br>
<p class="text-center">(<%= current_word.reference %>)</p><br>
<%= link_to "< Previous", current_word.previous if current_word.previous %>
<%= link_to "Next >", current_word.next if current_word.next %>
</div>
文字控制器:
class WordsController < ApplicationController
def show
end
private
helper_method :current_word
def current_word
@current_word ||= Word.find(params[:id])
end
end
发布于 2016-06-13 16:11:20
在你看来,你能这样做吗?
<% if current_word == Word.first %>
<%= link_to "Next >", current_word.next if current_word.next %>
<% elsif current_word == Word.last %>
<%= link_to "< Previous", current_word.previous if current_word.previous %>
<% else %>
<%= link_to "< Previous", current_word.previous if current_word.previous %>
<%= link_to "Next >", current_word.next if current_word.next %>
<% end %>
编辑
所以试试,
<%= link_to "< Previous", current_word.previous if current_word.previous.lesson_id == current_word.lesson.id %>
<%= link_to "Next >", current_word.next if current_word.next.lesson_id == current_word.lesson.id %>
这样,只要下一个单词或前面的单词来自不同的教训(有不同的lesson_id,链接就会消失)。
如果能用,请告诉我。
https://stackoverflow.com/questions/37800903
复制