-2

How can I write SQL queries for CRUD if I don't want to use the constructors & ghost methods' concept of the Rails. Eg. What if i want to INSERT INTO Values() instead of using Tablename.create()...and the saving it..

1 Answers1

0

You can execute SQL queries with ActiveRecord::Base.connection.

sql = <<-eos
  INSERT INTO table_name
  VALUES (1, 2, 3);
eos
result = ActiveRecord::Base.connection.execute(sql)

However, besides performing mass insertions of many rows at once there rarely is a good reason to do an insert with raw SQL. Your giving up all the goodies that come with Rails and ActiveRecord such as SQL injection protection, validations etc.

max
  • 96,212
  • 14
  • 104
  • 165
  • 1
    (Clearly a dupe as the link I provided shows; in general it's better to mark as a dupe than dupe an answer :) – Dave Newton Jan 24 '16 at 14:17