1

I run a insert statement on ruby on rails. But failed. This is the code:

class BookmarkController < ApplicationController
  def index

    if request.post?
    @user_new = Bookmark.new(params[:user_new])
    tags = @user_new.tags.split(",")
    @user_new = Bookmark.new(params[:user_new])
    query = "INSERT INTO bookmark (title , url, tags) VALUES (#{@user_new.title}, #{@user_new.url}, #{tags[0]})  "

    Bookmark.connection.execute(query);

    end   

  end

But the output is :

ActiveRecord::StatementInvalid in BookmarkController#index

SQLite3::SQLException: near ".": syntax error: INSERT INTO bookmark (title , url, tags) VALUES (abhir, www.mrabhiram.tumblr.com, tumblr)  

Can anyone suggest me the proper way to insert records using SQL insert statement?

Abhi Ram A
  • 305
  • 2
  • 4
  • 10
  • Raw SQL should never be in the controller. Also, you're duplicating functionality that comes with ActiveRecord. I recommend reading the [ActiveRecord guide](http://guides.rubyonrails.org/active_record_querying.html). – Mark Thomas Dec 13 '12 at 10:26

3 Answers3

2

Assuming Bookmark is subclassed from ActiveRecord, AR will save this for you - no need to write custom SQL - the save method will take care of this. You can read more about relevant ActiveRecord functionality here

class BookmarkController < ApplicationController
  def index

    if request.post?
    @user_new = Bookmark.new(params[:user_new])
    tags = @user_new.tags.split(",")
    @user_new = Bookmark.new(params[:user_new])
    #query = "INSERT INTO bookmark (title , url, tags) VALUES (#{@user_new.title}, #{@user_new.url}, #{tags[0]})  "

    #Bookmark.connection.execute(query);
    # The save method will insert the record into the database.
    @user_new.save()    

    end   

  end
Scott S
  • 2,696
  • 16
  • 20
2

You can write

    MOdel.connection.insert("INSERT INTO table_name(fields) VALUES('value')")

it's working...

Mandeep Singh
  • 983
  • 8
  • 9
0

You need quotes on your 'values' data. Something like:

query = "INSERT INTO bookmark (title , url, tags) VALUES ('#{@user_new.title}', '#{@user_new.url}', '#{tags[0]}')  "
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 4
    Don’t use this code! It is a classic example of SQL injection. Your users will be able to execute arbitrary SQL commands on your database. – Simon Perepelitsa Apr 13 '15 at 12:23
  • This answer will work here and is correct syntax, but as mentioned, you wouldn't want to do it here because it is unsafe and there are much better Rails ways to accomplish the same thing. – bigtex777 Aug 07 '17 at 18:22