我在很多方法中看到绑定(bind)作为参数,但没有任何文档。
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
绑定(bind)
是什么意思?- 如何使用?
最佳答案
当您的 SQL 包含问号 ?
时,绑定(bind)用于替换这些标记。例如,如果您有这样的查询:SELECT * from posts where id = 3
您可以用 Ruby 编写:
Post.find_by_sql(["SELECT * from posts where id = ?", 3])
我们已将 ?
与值 3
绑定(bind)。
如果我们有更多的 ?
,它们将按顺序与 binds 数组绑定(bind)。
如果 SQL 字符串中没有 ?
绑定(bind)将被忽略。
关于ruby-on-rails - Ruby:绑定(bind)在 ActiveRecord gem 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546052/