Does build protect against sql injection?
Example:
@post = @user.posts.build(params[:post])
@post.save
Didn't see build in the rails security docs.
Thanks!
Does build protect against sql injection?
Example:
@post = @user.posts.build(params[:post])
@post.save
Didn't see build in the rails security docs.
Thanks!
build
itself doesn't write anything to the database so SQL injection doesn't apply. When you call save
it doesn't matter whether the object was created via build
or via another mechanism such as passing attributes to new
or using individual attribute=
methods, the same code will be used to save your object to the database.
From the documentation on build:
Returns a new object of the collection type that has been instantiated with attributes and linked to this object through the join table, but has not yet been saved.
The save
method will escape any quotes etc in your attribute values using a method appropriate to the database you're using (e.g. MySQL) so that the resulting insert
or create
query is not susceptible to SQL injection. The same applies to update_attributes
and to any parameterised :conditions
that you pass to find
. The time when you need to be careful and may need to do some manual escaping is if you are ever passing literal strings to the database connection as queries.