You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_key is 'blog' and visible is true
  • Then we narrow it down to posts published before the current one
  • Ordering by published_at: :desc ensures we get the most recent valid older post (instead of just the last one in the unfiltered set)
  • .first grabs 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:10:47