【问题标题】:DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL). How to wrap in Arel?弃用警告:危险的查询方法(其参数用作原始 SQL 的方法)。如何包裹在 Arel 中?
【发布时间】:2019-07-25 20:15:42
【问题描述】:

我有这个问题:

@members = Member.where("EXTRACT(DOY FROM date_of_birth) >= ?", next_bdays).order('EXTRACT (DOY FROM date_of_birth) ASC').first(5)

它给出了错误:

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): "EXTRACT (DOY FROM (Arel.sql \"DATE(date_of_birth)\")) ASC". Non-attribute arguments will be disallowed in Rails 6.0. This method should not be called with user-provided values, such as request parameters or model attributes. Known-safe values can be passed by wrapping them in Arel.sql().

可以做什么?如何在 Arel 中包装 date_of_birth?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-6


    【解决方案1】:

    根据 DEPRECATION,您可以将其包装如下:

    .order(Arel.sql('EXTRACT (DOY FROM date_of_birth) ASC'))
    

    甚至

    .order(Arel.sql('EXTRACT (DOY FROM date_of_birth)').asc)
    

    不过,我会更进一步,采取以下措施:

    custom_clause = Arel::Nodes::NamedFunction.new('EXTRACT',
      [Arel::Nodes::SqlLiteral.new("DOY FROM members.date_of_birth")]
    )
    

    这将生成所需的 SQL,并且可以像这样作为 where 子句的一部分重用

    @members = Member
                .where(custom_clause.gteq(next_bdays))
                .order(Arel.sql(custom_clause.to_sql).asc)
                .first(5)
    

    这将产生以下查询。 (假设next_bdays == 123)

    SELECT 
      members.* 
    FROM 
      members 
    WHERE 
      EXTRACT(DOY FROM members.date_of_birth) >= 123  
    ORDER BY 
      EXTRACT(DOY FROM members.date_of_birth) ASC
    LIMIT 5
    

    Some Raw SQL will be acceptable 只要它遵循标准的 column_name 或 table.column_name 语法 Whitelist can be found here 并且一如既往地支持 Arel 对象 Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      相关资源
      最近更新 更多