Rails中如何跳过/忽略不符合条件的文章链接数据?
Hey Jake, I’ve got you covered here! The issue with your current setup is that your previous method isn’t filtering for the criteria you care about (blog_key: 'blog' and visible: true)—it’s just grabbing any older post. That’s why you have to add extra checks in the view, and it won’t skip past invalid posts to find the next valid one. Let’s fix this properly:
Step 1: Update the Model Methods
Move the filtering logic directly into your previous and next methods so they only return posts that meet your requirements. This keeps your view clean and follows Rails’ "fat model, skinny view" best practice.
Updated previous method:
def previous SpudPost.where(blog_key: 'blog', visible: true) .where("published_at < ?", published_at) .order(published_at: :desc) .first end
- We first filter for posts where
blog_keyis'blog'andvisibleistrue - Then we narrow it down to posts published before the current one
- Ordering by
published_at: :descensures we get the most recent valid older post (instead of just the last one in the unfiltered set) .firstgrabs that top result
Updated next method:
def next SpudPost.where(blog_key: 'blog', visible: true) .where("published_at > ?", published_at) .order(published_at: :asc) .first end
This works the same way, but looks for posts published after the current one, ordered ascending to get the earliest valid next post.
Step 2: Simplify the View Code
Now that your model methods only return valid posts (or nil if none exist), you can strip out the extra checks in your view:
<% if @post.previous %> <%= link_to 'Previous Post', blog_post_path(@post.previous.url_name)%> <% else %> <%= link_to 'Home', '/blog/home' %> <% end %>
If there’s a valid previous post, it’ll show the link—if not, it falls back to the Home link, just like you wanted.
This approach ensures you’ll always get the nearest valid post (skipping any invalid ones in between) instead of stopping at the first invalid post and jumping to home.
内容的提问来源于stack exchange,提问作者Jake

