Raw Insert Query with ActiveRecord

These past days have taken me to a place that I need to learn more about executing a raw query, without relying on generated active record object (existing model classes).

Last week, I wrote a lib, that I think, required me to wrote it with custom or raw query. My research was filled with these kind of results


I used it actually. But, until I find it hard to produce a query string that free from SQL injection. Anyone knows how to do it?

I tried looking for it. Some showed using the object class execute the raw query along with the input parameters and some showed using other functions provided by ActiveRecord::Base. But, it still kept me in the dark.

Well, the only goal that I want to achieve is, to make an insert query with input parameters. And so far, Arel is the best answer for this.

What I did to achieve this was

> manager = Arel::InsertManager.new(ActiveRecord::Base)
> table = Arel::Table.new(:stations)
> manager.into(table)
> manager.insert([ [table[:user_id], 1], [table[:station_id], 1], [table[:label], 'this is a label'] ])
> manager.to_sql
#"INSERT INTO `stations` (`user_id`, `station_id`, `label`) VALUES (1, 1, 'adfasdfad')"

Well, I think the query string is now safe from SQL injection and it can be used against the execute function from ActiveRecord.


One thought on “Raw Insert Query with ActiveRecord

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s