Abhi Ram A
Abhi Ram A

Reputation: 305

How can i write a insert statement in ruby on rails?

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?

Upvotes: 1

Views: 17369

Answers (3)

Mandeep Singh
Mandeep Singh

Reputation: 1003

You can write

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

it's working...

Upvotes: 2

Scott S
Scott S

Reputation: 2746

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

Upvotes: 2

Michael Durrant
Michael Durrant

Reputation: 96594

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]}')  "

Upvotes: 0

Related Questions