我正在关注此stackoverflow帖子How can i store and show only the last 5 NEWS seen by the current user?
但是,我认为我收到此错误(无法找到带有'id'= python-0的文章),因为我正在使用friendly_id gem生成文章网址。有解决方法吗?
应用程序控制器
before_action :recently_viewed_articles
def recently_viewed_articles
session[:article_id] ||= []
session[:article_id] << params[:id] unless params[:id].nil?
session[:article_id].delete_at(0) if session[:article_id].size >= 5
end
页面控制器
def home
@recent_articles = session[:article_id]
@feed = current_user.feed
end
_feed.html.erb
<div class = "container">
<div class = "row">
<div class = "col-md-9">
<%= render @feed %>
</div>
<div class = "col-md-3">
<div class="list-group">
<button type="button" class="list-group-item list-group-item-action active">
Recently visited
</button>
<% @recent_articles.each do |recent| %>
<button type="button" class="list-group-item list-group-item-action">
<%= link_to "#{Article.find(recent).title}", article_path(Article.find(recent)) %>
</button>
<% end %>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
根据文档,我相信您应该使用friendly
范围。
Article.friendly.find(recent)
答案 1 :(得分:0)
https://github.com/norman/friendly_id
你有什么设置应该做的吗?如果还没有,那么你可以使用:
Article.friendly.find('python-0')
否则,在您的文章模型中:
friendly_id :title, use: [:slugged, :finders]
然后你可以打电话
Article.find('python-0')