跳到內容 跳到搜尋
方法
S

常數

VERSION = "10.0.0"
 

類別公開方法

sql(sql_string, *positional_binds, retryable: false, **named_binds)

包裝已知安全的 SQL 字串以傳遞給查詢方法,例如

Post.order(Arel.sql("REPLACE(title, 'misc', 'zzzz') asc")).pluck(:id)

應特別小心避免 SQL 注入弱點。此方法不應與不安全值(例如要求參數或模型屬性)一併使用。

參閱安全指南以取得更多資訊。

若要建構更複雜的查詢片段(包括可能使用使用者提供的值),sql_string 可能包含對應於其他參數的?:key佔位符號。請注意,這種行為僅適用於呼叫中提供約束值參數時;如果不使用這些參數,佔位符號令牌沒有特殊含義,且會原樣傳遞至查詢中。

:retryable 選項可用於將 SQL 標記為安全的重試。僅在 SQL 是具有冪等性的情況下使用此選項,因為它可能會執行多次。

# File activerecord/lib/arel.rb, line 52
def self.sql(sql_string, *positional_binds, retryable: false, **named_binds)
  if positional_binds.empty? && named_binds.empty?
    Arel::Nodes::SqlLiteral.new(sql_string, retryable: retryable)
  else
    Arel::Nodes::BoundSqlLiteral.new sql_string, positional_binds, named_binds
  end
end