SQL INSERTステートメント(意図的にActiveRecordを使用しない)を記述して、最終的に一度に多数の行を挿入しようとしています。
inserts.push "('#{x}', #{p}, '#{day.strftime("%Y-%m-%d")}', #{student.id}, '#{created_at}', '#{created_at}', '#{session}')"
sql = "INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES #{inserts.join(", ")}"
conn = ActiveRecord::Base.connection
conn.execute sql
x
しかし、の値がであるため、エラーが発生します"\"
。これを回避してバックスラッシュ文字をMySQLDBに正常に挿入するにはどうすればよいですか?
シンプルなはずだと思いますし、おそらくそうでしょうが、私はそれを解決しようと最後までやり遂げなければなりません。
エラーメッセージ:
>> Attendance.parse_attendance_string Student.find(1), "\\", DateTime.new(2012,9,1)
Student Load (0.7ms) SELECT `students`.* FROM `students` WHERE `students`.`id` = 1 LIMIT 1
(0.4ms) INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')' at line 1: INSERT INTO attendance_marks (mark_code, present, date_recorded, student_id, created_at, updated_at, sess) VALUES ('\', 1, '2012-09-01', 1, '2012-08-03 15:58:19', '2012-08-03 15:58:19', 'AM')
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `query'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `log'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:233:in `execute'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.2.0/lib/active_record/connection_adapters/mysql2_adapter.rb:214:in `execute'
from /Users/mike.campbell/projects/cpoms_messy/app/models/attendance.rb:76:in `parse_attendance_string'
from (irb):115
>>