views:

32

answers:

2

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!

+2  A: 

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.

mikej
ok, that makes sense. but would the above code sample filter out sql injection? that part is still unclear. thanks!
bandhunt
@bandhunt I have updated the answer to clarify that the code in your question is fine and will filter out SQL injection attempts.
mikej
A: 

Duplicate: http://stackoverflow.com/questions/2144778/sql-injection-prevention-for-create-method-in-rails-controller

dombesz
This is not really a duplicate as it doesn't ask about using `build`. Also, possible duplicates should probably be posted as comments on the question rather than answers.
mikej