我在 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 插入语句插入记录的正确方法?
最佳答案
假设 Bookmark
是 ActiveRecord
的子类,AR 会为您保存它 - 无需编写自定义 SQL - save
方法将采用关心这个。您可以阅读有关 ActiveRecord 功能的更多信息 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
关于database - 我如何在 ruby on rails 中编写插入语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845514/