开发者

Rails - escaping SQL params

I am doing some plain SQLs in my rails mod开发者_StackOverflowel (for purists this is just for complex SQLs :)

Since I am not using find*/condition methods, is there a helper method that I can use straight to do that?


The quote method on the connection object escapes strings. When building up queries, use sanitize_sql_for_conditions to convert ActiveRecord conditions hashes or arrays to SQL WHERE clauses.

The methods in ActiveRecord::ConnectionAdapters::DatabaseStatements are handy for direct queries, in particular the ones starting with select_.


Rails uses sanitize_sql_for_conditions internally for dealing with placeholders. Of course, that method is protected so you can't (cleanly) use it outside of an ActiveRecord model. You can get around the protectedness using send:

escaped_string = Model.send(:sanitize_sql_for_conditions, [
        'id = ? and name = ?',
        params[:id], params[:name]
    ]
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜