Escaping values in Rails (similar to mysql_real_escape_string())

后端 未结 6 1859
我在风中等你
我在风中等你 2020-12-14 00:54

I know about prepared statements, but if I\'m using raw SQL, does ActiveRecord have a way to manually escape values?

Something like this would be nice:



        
6条回答
  •  忘掉有多难
    2020-12-14 01:39

    In case somebody is looking for a more concrete example of @jemminger's solution, here it is for bulk insert:

    users_places = []
    users_values = []
    timestamp = Time.now.strftime('%Y-%m-%d %H:%M:%S')
    params[:users].each do |user|
        users_places "(?,?,?,?)"
        users_values << user[:name] << user[:punch_line] << timestamp << timestamp
    end
    
    bulk_insert_users_sql_arr = ["INSERT INTO users (name, punch_line, created_at, updated_at) VALUES #{users_places.join(", ")}"] + users_values
    begin
        sql = ActiveRecord::Base.send(:sanitize_sql_array, bulk_insert_users_sql_arr)
        ActiveRecord::Base.connection.execute(sql)
    rescue
        "something went wrong with the bulk insert sql query"
    end
    

    Here is the reference to sanitize_sql_array method in ActiveRecord::Base, it generates the proper query string by escaping the single quotes in the strings. For example the punch_line "Don't let them get you down" will become "Don\'t let them get you down".

提交回复
热议问题