What is the purpose of binding ActiveRecord :: Relation #?

Just out of curiosity - I read the Relation :: QueryMethods module docs and found this method:

def bind(value) relation = clone relation.bind_values += [value] relation end 

Does anyone know what it is? I tried to find it myself, but could not.

UPDATE

I monitored the use of @bind_values to a bottomless depth ActiveRecord::ConnectionAdapters - the values ​​are transferred and run before the execution of low-level SQL statements. It seems that individual adapters can use them. I assume this is due to prepared statements like SELECT * FROM 'table' WHERE 'field' = ? but i'm stuck here. Anyone?

+6
source share
1 answer

First, I would like to explain the find_by_sql method provided by ActiveRecord. It looks like this method can be used as follows:

 Post.find_by_sql("SELECT title FROM posts WHERE author_id = ?", [author_id]) 

The second parameter is called "binds", and it is an array of variables that matches the question marks in the query. You really want to use the binds array to insert parameters into your query, because it avoids a lot of SQL injection , which can occur if you did the binding yourself:

 Post.find_by_sql("SELECT title FROM posts WHERE author_id = #{author_id}") 

So how is this related to ActiveRecord :: Relation? The point of AREL is that you can create a query a little at a time by calling methods in an ActiveRecord :: Relation object. There are a bunch of these methods, and here are some of their lists:

http://apidock.com/rails/v3.2.8/ActiveRecord/QueryMethods

Thus, the bind method creates a new object, cloning the current one, adds the specified value to the bind_values list, and then returns a new object. In the end, when a relation is used to generate a query, this value will be used to create the query. One example where bind_values is passed to find_by_sql is in the exec_queries method:

 @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values) 

You can find "bind_values" in the activerecord stone, and you will find several similar places in which it is used.

I would have thought that the bind method would be called where , but it does not seem to be called anywhere in activerecord. Maybe this is an older design. I do not think you should call bind in your application.

+9
source

All Articles