我有一個名爲posts的資源,其中有很多。但是,每個帖子可以有多個標籤。我希望用戶只能從選擇的標記中轉到上一篇文章和下一篇文章。我在之前的數據庫中使用過所有文章,但是當我點擊一個標籤並顯示了所有標籤時,prev/next不遵守標籤。Rails 5上一篇或下一篇文章只從某個標記
如果我訪問與routes.rb,get 'tags/:tag', to: 'posts#index', as: :tag
中定義的代碼相關聯的url,它將列出索引中的所有標籤。我不希望這樣,我希望用戶能夠點擊上一個或下一個,並且只對與標籤關聯的帖子執行此操作。
注:我使用的是friendly_id寶石
控制器/ posts_controller.rb
def index
@posts = Post.all
if params[:tag]
@posts = Post.tagged_with(params[:tag])
else
@posts = Post.all
end
end
型號/ post.rb
# tags
acts_as_taggable # Alias for acts_as_taggable_on :tags
def next
Post.where("id > ?", id).order(id: :asc).limit(1).first
end
def prev
Post.where("id < ?", id).order(id: :desc).limit(1).first
end
show.html .erb
<%= link_to "← Previous Question", @post.prev, :class => 'button previous-question' %>
<%= link_to "Next Question →", @post.next, :class => 'button next-question' %>
的routes.rb
# TAGS
get 'tags/:tag', to: 'posts#index', as: :tag
',但是當我點擊廣告代碼,並顯示所有tags'你能解釋一下痘痘嗎?它會顯示所有標籤?你能爲此添加代碼嗎? –
我已更新帖子@NarasimhaReddy – mazing
因此,當標籤被點擊並且其相關帖子被顯示時,你想爲這些帖子列表分頁? – arjun