繁体   English   中英

Ruby:ActiveRecord gem中的绑定是什么意思?

[英]Ruby: What does binds mean in ActiveRecord gem?

我在许多方法中看到了绑定作为参数,但没有任何文档。

例如Rails源代码

def find_by_sql(sql, binds = [], preparable: nil, &block)
  result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds, preparable: preparable)
  column_types = result_set.column_types.dup
  columns_hash.each_key { |k| column_types.delete k }
  message_bus = ActiveSupport::Notifications.instrumenter

  payload = {
    record_count: result_set.length,
    class_name: name
  }

  message_bus.instrument("instantiation.active_record", payload) do
    result_set.map { |record| instantiate(record, column_types, &block) }
  end
end
  1. 什么是binds意味着什么?
  2. 如何使用它?

当您的SQL包含问号? 绑定用于替换这些标记。 例如,如果您有这样的查询: SELECT * from posts where id = 3您可以使用Ruby编写:

Post.find_by_sql(["SELECT * from posts where id = ?", 3])

我们已经绑定了? 3 如果我们有更多? 它们将按顺序与绑定数组绑定。 如果没有? 在SQL字符串中绑定被忽略。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM