Active Record在条件下加入params

时间:2013-03-06 18:02:06

标签: ruby-on-rails activerecord

我不确定我是否知道在活动记录中编写此SQL查询的最佳方法,而无需手动编写。基本上我想写这两个查询的组合。

此查询本质上是我尝试重新创建的联接。我想确保返回的任何条目只是那些图像的image_path_processing标志设置为false。

@entries = ContestEntry.joins(:entry_images).where(contest_id: @contest.id, entry_images: {
        image_path_processing: false
        }).limit(10)

然而,我遇到的问题是我正在编写的问题是我需要在url中包含params而且我不确定上面的语法是否正确删除了sql_injection

以下是我尝试将条件联接添加到。

@entries = ContestEntry.where("contest_id = ? and created_at > ?",
      params[:contest_id], Time.at(params[:after].to_i + 1))

3 个答案:

答案 0 :(得分:2)

你能试试吗?

@entries = ContestEntry.joins(:entry_images).
                        where(contest_id: params[:contest_id],
                              entry_images: { image_path_processing: false }).
                        where('contest_entries.created_at > ?', Time.at(params[:after].to_i+1)).
                        limit(10)

答案 1 :(得分:1)

首先,请阅读此文档:http://guides.rubyonrails.org/security.html#sql-injection

在当天,主要支持的语法是

ContestEntry.where("contest_id = ?", params[:contest_id])

但现在你也可以使用更简单,更红宝石的

ContestEntry.where(:contest_id => params[:contest_id])

这两种方法都会通过sql清理程序传递params,以防止文档中描述的sql注入攻击。

还有几点:

  1. 我不确定如何为除了相等之外的任何东西实现后一种语法。
  2. 您最近听到的有关SQL注入的问题,不适用于您正在使用的语法。它们适用于动态查找器。
  3. 最后,你不应该接受我的话。 ruby开发人员给我的最好的建议之一是'使用irb来学习ruby'。如果您对某些内容的工作方式有疑问,请加载irb并对其进行测试。在您的情况下,您正在实施rails,因此您可以使用完整的控制台。

    sql_injection_params = "anything' OR 'x'='x"
    # This string variant tells active record to use sql as is 
    Model.where("name = '#{sql_injection_params}'").to_sql # bad
    # This array variant tells active record to sanitize
    Model.where('name = ?', sql_injection_params).to_sql # good
    # This hash variant tells active record to sanitize
    Model.where(:name => sql_injection_params).to_sql # good
    

    to_sql调用将显示基于查询构建的原始SQL活动记录。只需更改上面的示例即可使用您的数据,您应该更好地了解导轨下的导轨。

答案 2 :(得分:0)

@entries = ContestEntry.where("contest_id = ? and created_at > ?",
      params[:contest_id], Time.at(params[:after].to_i + 1))

似乎是完全避免用户输入结果的SQL注入的方法......