← Back to Upcase

Using raw sql in rails


(Gary Tsai) #1

My manager is is unfamiliar with rails but knows a lot of SQL sometimes has me resort to sql if I don’t know how to query something. I know things can be done in sql. Granted I understand with complex queries it might be “simpler” to do some raw SQL.

My thing is why use rails if you’re just going to be using raw sql as opposed to ActiveRecord. Plus, SQL is REALLY messy and I’d hate to mix my code up with raw SQL.

Any thoughts or opnions?


(Geoff Harcourt) #2

Using ActiveRecord makes doing things like chaining queries much easier, which increases your ability to reuse code.

ActiveRecord, while it isn’t proof against SQL injection, does significantly improve your protection against SQL injection because of something subtle that you might miss when constructing a custom query. @seangriffin had a nice blog post about using Arel for queries AR can’t handle: http://robots.thoughtbot.com/using-arel-to-compose-sql-queries


(Gary Tsai) #3

Great thanks for the contribution! I wish I could convince my manger of that. :frowning: I’m trying to figure a reason and way to show him but can’t seem to. Perhaps it’s a time issue and he doesn’t want me to spend time abstracting SQL queries he makes in 5 minutes while I construct a method that could take me an hour to two (I’m a junior engineer - still learning on the job).