maz*_*ing 10 ruby ruby-on-rails
我有一个名为posts的资源,其中有很多.但是,每个帖子可以有多个标签.我希望用户能够从所选的标签转到上一篇文章和下一篇文章.我让它适用于前一个数据库中的所有帖子,但当我点击一个标签并显示所有标签时,prev/next不符合标签的内容.
如果我访问与routes.rb中定义的代码相关联的url get 'tags/:tag', to: 'posts#index', as: :tag,它将列出索引中的所有标记.我不希望这样,我希望用户能够单击上一个或下一个,并且仅对与标签关联的帖子执行此操作.
注意:我使用的是friendly_id gem
控制器/ posts_controller.rb
def index
@posts = Post.all
if params[:tag]
@posts = Post.tagged_with(params[:tag])
else
@posts = Post.all
end
end
Run Code Online (Sandbox Code Playgroud)
车型/ 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
Run Code Online (Sandbox Code Playgroud)
show.html.erb
<%= link_to "? Previous Question", @post.prev, :class => 'button previous-question' %>
<%= link_to "Next Question ?", @post.next, :class => 'button next-question' %>
Run Code Online (Sandbox Code Playgroud)
的routes.rb
# TAGS
get 'tags/:tag', to: 'posts#index', as: :tag
Run Code Online (Sandbox Code Playgroud)
我想你将不得不传递那个tag参数(尽管你应该把它作为一个辅助方法)
车型/ post.rb
def next tag
Post.where("id > ?", id).tagged_with(tag).order(id: :asc).limit(1).first
end
def prev tag
Post.where("id < ?", id).tagged_with(tag).order(id: :desc).limit(1).first
end
Run Code Online (Sandbox Code Playgroud)
节目
<%= link_to "? Previous Question", post_path(@post.prev(current_tag).id, tag: current_tag), :class => 'button previous-question' %>
<%= link_to "Next Question ?", post_path(@post.next(current_tag).id, tag: current_tag), :class => 'button next-question' %>
Run Code Online (Sandbox Code Playgroud)
控制器/ posts_controller.rb
class PostsController < ApplicationController
helper_method :current_tag
#def show
#def index
private
def current_tag
params[:tag]
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
350 次 |
| 最近记录: |