1

我在 ruby​​ on rails 上运行插入语句。但是失败了。这是代码:

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

但输出是:

ActiveRecord::StatementInvalid in BookmarkController#index

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

谁能建议我使用 SQL 插入语句插入记录的正确方法?

4

3 回答 3

2

你可以写

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

它正在工作...

于 2014-01-31T06:48:58.193 回答
2

假设Bookmark是 的子类ActiveRecord,AR 将为您保存这个 - 无需编写自定义 SQL - 该save方法会处理这个问题。您可以在此处阅读有关相关 ActiveRecord 功能的更多信息

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
于 2012-12-12T18:04:15.820 回答
0

您需要在“价值”数据上加上引号。就像是:

query = "INSERT INTO bookmark (title , url, tags) VALUES ('#{@user_new.title}', '#{@user_new.url}', '#{tags[0]}')  "
于 2012-12-12T17:45:41.943 回答