【问题标题】:Rails 3: Search method returns all models instead of specifiedRails 3:搜索方法返回所有模型而不是指定
【发布时间】:2013-02-12 13:51:02
【问题描述】:

我正在尝试做的事情: 我有一个模型“Recipe”,在其中我定义了一个“search”方法,该方法从复选框中获取一组字符串(我称它们为标签),并且单个字符串。这个想法是在数据库中搜索包含字符串的“名称”或“指令”中包含任何内容的食谱,并且还具有与它的“标签”属性匹配的任何标签。

问题:搜索方法返回我数据库中的所有食谱,并且似乎根本无法通过特定参数查找。

控制器中的动作方法:

def index
      @recipes = Recipe.search(params[:search], params[:tag])
      if !@recipes
        @recipes = Recipe.all
      end
      respond_to do |format|
      format.html 
      format.json { render json: @recipe }
    end
  end

我的模型中的搜索方式:

  def self.search(search, tags)
    conditions = ""

    search.present? do
        # Condition 1: recipe.name OR instruction same as search?
        conditions = "name LIKE ? OR instructions LIKE ?, '%#{search[0].strip}%', '%#{search[0].strip}%'"

     # Condition 2: if tags included, any matching?
      if !tags.empty?
        tags.each do |tag|
          conditions += "'AND tags LIKE ?', '%#{tag}%'"
        end
      end
      end
    # Hämtar och returnerar alla recipes där codition 1 och/eller 2 stämmer.
        Recipe.find(:all, :conditions => [conditions]) unless conditions.length < 1
  end

任何想法为什么它返回所有记录?

【问题讨论】:

  • 是的,这绝对是真的。如果你有更好的例子,请赐教。这就是我到目前为止的想法。
  • 您的标签是如何在参数中返回的?作为数组还是字符串?如果它们只是一个字符串,您可能必须先对它们运行 split()
  • 我很确定这是一个字符串数组,例如 ["meat", "fish"]。

标签: ruby-on-rails search methods


【解决方案1】:

如果你使用的是rails 3,那么链式查找条件很容易

def self.search(string, tags)
  klass = scoped

  if string.present?
    klass = klass.where('name LIKE ? OR instructions LIKE ?', "%#{string}%", "%#{string}%")
  end

  if tags.present?
    tags.each do |tag|
      klass = klass.where('tags LIKE ?', "%#{tag}%")
    end
  end

  klass
end

【讨论】:

    【解决方案2】:

    当你这样做时

    search.present? do
      ...
    end
    

    该块的内容被忽略 - 将一个块传递给一个不需要的函数是完全合法的,但是除非函数决定调用该块,否则该块不会被调用。结果,您的条件构建代码都不会被执行。你可能是说

    if search.present?
      ...
    end
    

    正如 jvnill 所指出的,一般来说,操作范围比手动构建 SQL 片段要好得多(也更安全)

    【讨论】:

    • 谢谢。我对块行为知之甚少。我可能需要重新考虑一下整个事情。 jvnills 方式看起来不错,但如果标签存在,我需要将标签作为必须的“where”语句。任何方式,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多