简体   繁体   English

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

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

I saw binds as argument in lots of methods, but without any documentation. 我在许多方法中看到了绑定作为参数,但没有任何文档。

eg Rails Source code 例如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. what does binds mean? 什么是binds意味着什么?
  2. How to use it? 如何使用它?

When your SQL contain question marks ? 当您的SQL包含问号? the binds are used to replace these marks. 绑定用于替换这些标记。 For example if you have a query like this: SELECT * from posts where id = 3 you can write in Ruby: 例如,如果您有这样的查询: SELECT * from posts where id = 3您可以使用Ruby编写:

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

We have binded the ? 我们已经绑定了? with the value 3 . 3 If we have more ? 如果我们有更多? they will be binded with the binds array in that order. 它们将按顺序与绑定数组绑定。 If there are not ? 如果没有? in the SQL string binds are ignored. 在SQL字符串中绑定被忽略。

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

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