【问题标题】:Index Action Issue in Rails ControllerRails 控制器中的索引操作问题
【发布时间】:2012-11-12 02:09:14
【问题描述】:

可能是一个愚蠢的问题,所以我提前为此道歉:

我有一个Item Controller,我使用它的索引操作来显示所有items (duh)。现在,我想过滤显示的项目(这里,只是标题中包含“鞋子”的项目)。

不幸的是,我无法在 index 操作下定义 @item = Item.find(params[:id]) 语句。

我在 ItemsController#index 中得到可怕的 ActiveRecord::RecordNotFound ---- 找不到没有 ID 错误的项目。

有什么想法吗?

物品控制器

def index
     @item = Item.find(params[:id])
     @items = Item.where(@item.title =~ /shoes/i).paginate(:page => params[:page], :per_page => 30)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @items }
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby controller


    【解决方案1】:

    这实际上就是你想要的。你的尝试毫无意义。

      def index
         @items = Item.where("title ILIKE '%shoes%'").paginate(:page => params[:page], :per_page => 30)
    
        respond_to do |format|
          format.html # index.html.erb
          format.json { render json: @items }
        end
      end
    

    编辑:

    为了与所有受支持的数据库兼容,您似乎可以这样做

    item=Item.arel_table
    Item.where(item[:title].matches('%shoes%'))
    

    【讨论】:

    • ILIKE 的存在(以及 LIKE 的区分大小写)是特定于数据库的,因此如果您关心便携式解决方案,您通常会need a bit of hackery。 AFAIK,ILIKE 是特定于 PostgreSQL 的。也就是说,你走在正确的轨道上。
    • 生病了——这行得通。你能解释一下你做了什么吗? (主要是“title ILIKE '%shoes%'”部分?
    • 是否有一种适用于所有方面的 RegEx 方法?
    • 好吧,我认为 LIKE 或 ILIKE 是在 SQL 查询中使用某种正则表达式的一种方式,在这种情况下,正如 @muistooshort 所说,它是特定于 postgresql 的。这是有关它的一些信息postgresql.org/docs/7.3/static/functions-matching.html
    • @abhir:大多数数据库都以一种或另一种形式支持真正的正则表达式,但是,唉,它们的做法都不同。而且您可能想查看 PostgreSQL 文档的当前版本,7.3 相当长:postgresql.org/docs/current/static/functions-matching.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多