Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Interpolation from Ruby on Rails Tutorial

this is the code from Ruby on Rails Tutorial by MH:

def feed
    following_ids = "SELECT followed_id FROM relationships
                     WHERE  follower_id = :user_id"
    Micropost.where("user_id IN (#{following_ids})
                     OR user_id = :user_id", user_id: id)
end

Is this SQL safe? Because many people told me never use interpolation but use escaped code ever (with ? in this case). So is this code safe?

like image 719
rod Avatar asked May 16 '26 21:05

rod


1 Answers

Yes, this is safe.

There is no interpolation, in fact: the whole query could be written as

Micropost.where("user_id IN (
     SELECT followed_id FROM relationships
      WHERE  follower_id = :user_id)
   OR user_id = :user_id", user_id: id)

but for the sake of clarity, the first query was extracted into it’s own variable.

Interpolation must be avoided when the interpolated string comes from the outside. This string is constructed by you, right here, hence there is no risk of SQL injection or like.


Examples

safe, id is determined:

id = 42
"SELECT * FROM users WHERE users.id = #{id}"

unsafe, params[:id] comes from the outside and might be dangerous:

"SELECT * FROM users WHERE users.id = #{params[:id]}"
like image 172
Aleksei Matiushkin Avatar answered May 19 '26 14:05

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!