Creating urls when not using integer as identifier?

So, I am creating a blog engine that has / articles / then -the-article-permalink as its URL structure. I need to have the previous and next links that will go to the next pub_date article, 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.find(: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 article model, I have the following:

 def to_param self.permalink end 

I get the following error message:

 article_url failed to generate from {:action=>"show", :controller=>"articles", :id=>nil}, expected: {:action=>"show", :controller=>"articles"}, diff: {:id=>nil} 

Without the next and the next, everything works fine, but I have no idea why this is not working. Anyone want to help?

+4
source share
4 answers

Solved my own problem because I only had 2 entries, it always found a null entry. 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 bloated problem, but I thought I would add a solution for those who are faced with this in the future.

+1
source
 @next_picture = Article.find(:first, :conditions => [ "pub_date > ?", @article.pub_date]) 

probably should be as follows:

 @next_article = Article.find(:first, :conditions => [ "pub_date > ?", @article.pub_date]) 

(I changed @next_picture to @next_article)

0
source

Paste the template <% debugger %> into your template and then check what @next_article.permalink ? I suspect that the permalink is empty (empty string or zero).

In addition, only in general can friendly_id be recommended as a more reliable solution to this problem (including modifying other permalinks and features).

0
source

You can use will_paginate for this problem and set the number of articles on page 1, and use named_scope to order pub_date articles. Then your next and previous links will work. The URLs for the next and previous will show the page number, not the date, but you can probably change the behavior of the parameters sent to the action to use the date instead of the page number.

0
source

Source: https://habr.com/ru/post/1305879/


All Articles