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

Ruby on Rails新手:如何处理带参数的GET请求

实现按查询参数过滤文章的解决方案

Hey there! Glad you've gotten through the Rails getting started guide—great job taking the next step to customize your app. Let's get that filtering logic working for your articles index.

修改控制器逻辑

你只需要更新app/controllers/articles_controller.rb里的index方法,根据special查询参数来决定返回的文章集合:

class ArticlesController < ApplicationController
  def index
    if params[:special] == 'true'
      # 匹配标题包含"token"的文章
      @articles = Article.where("title LIKE ?", "%token%")
    else
      # 默认返回所有文章(包括special=false或参数不存在的情况)
      @articles = Article.all
    end
  end
end

代码解释

  • HTTP请求的查询参数都是字符串类型,所以我们要和'true'(带引号)比较,而不是布尔值true
  • LIKE ?是ActiveRecord的安全查询方式,%token%是SQL通配符,表示匹配任意位置包含"token"的标题(如果需要忽略大小写,可以用ILIKE替代LIKE,这取决于你的数据库类型)
  • 当special参数为false、不存在或者是其他任意值时,都会返回所有文章,完全符合你的需求

视图和路由不需要修改

你的视图app/views/articles/index.html.erb已经在遍历@articles,所以不需要做任何改动——控制器已经把过滤好的集合传给视图了。

路由方面,resources :articles已经生成了正确的index路由,直接访问:

  • /articles?special=false(或者直接/articles)会返回所有文章
  • /articles?special=true会返回标题含"token"的文章

内容的提问来源于stack exchange,提问作者mike zenon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:40:51