1

Ruby on Railsでinsertステートメントを実行します。しかし、失敗しました。これはコードです:

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

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 に答える
2

あなたは書ける

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

それは働いています...

于 2014-01-31T06:48:58.193 に答える
0

「値」データには引用符が必要です。何かのようなもの:

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