So I'm building a blog engine which has /articles/then-the-article-permalink as it's URL structure. I need to have prev and next links which will jump to the next article by pub_date, my code looks like this:
In my articles#show
@article = Article.find_by_permalink(params[:id])
@prev_article = Article.find(:first, :conditions => [ "pub_date < ?", @article.pub_date])
@next_article = Article.f开发者_运维百科ind(:first, :conditions => [ "pub_date > ?", @article.pub_date])
And in my show.html.erb
<%= link_to "Next", article_path(@next_article) %>
<%= link_to 'Prev', article_path(@prev_article) %>
In my articles model I have this:
def to_param
self.permalink
end
The specific error message I get is:
article_url failed to generate from {:action=>"show", :controller=>"articles", :id=>nil}, expected: {:action=>"show", :controller=>"articles"}, diff: {:id=>nil}
Without the prev and next everything is working fine but I'm out of ideas as to why this isn't working. Anyone want to help?
Solved my own problem, because I only had 2 records it was always finding a nil record. I changed the code in the views to:
<%= link_to "Next", article_path(@next_article) if !@next_article.nil? %>
<%= link_to 'Prev', article_path(@prev_article) if !@prev_article.nil? %>
Stupid and overblown problem, but I thought I'd add the solution for anyone that comes across this in future.
@next_picture = Article.find(:first, :conditions => [ "pub_date > ?", @article.pub_date])
should probably be this:
@next_article = Article.find(:first, :conditions => [ "pub_date > ?", @article.pub_date])
(I changed @next_picture to @next_article)
Stick in a <% debugger %>
in your template and then check what the value of the @next_article.permalink
is? I suspect the permalink is blank (either empty string or nil).
Also, just in general, can I recommend the friendly_id as a more robust solution to this problem (including changing permalinks and other features).
You could use will_paginate for this problem and set the number of of articles per page to 1, and use a named_scope to order the articles by pub_date. Then your next and previous links would just work. The URLs for next and previous would show the page number rather than the date, but you could probably modify the behaviour of the params sent to the action to use the date instead of the page number.
精彩评论