简体   繁体   中英

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

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?
  2. How to use it?

When your SQL contain question marks ? 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:

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

We have binded the ? with the value 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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