Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off MySQL strict mode in Rails

Tags:

Upgrading to Rails 4, it seems MySQL strict mode is now on by default for Rails connections. I say this because my Rails app is getting "Mysql2::Error: Data too long for column" when saving a string value longer than 255 characters. Yet, I paste the same query into MySQL console (where global strict mode is reported to be off) and it works fine, just with truncation warnings. As further evidence, it says here "Rails 4 both use strict mode by default".

My question is how can I turn strict mode off from the Rails app? I'd rather avoid upgrading everything to support it right now.

like image 462
mahemoff Avatar asked Jan 29 '14 01:01

mahemoff


People also ask

How do I turn off InnoDB strict mode?

You can also enable or disable InnoDB strict mode at run time with the statement SET [GLOBAL|SESSION] innodb_strict_mode= mode , where mode is either ON or OFF . Changing the GLOBAL setting requires the SUPER privilege and affects the operation of all clients that subsequently connect.


2 Answers

You can set strict mode in your database.yml using strict: false as follows:

production:   host: ...   username: ...   strict: false 

https://api.rubyonrails.org/v4.2.8/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html

like image 140
nimblegorilla Avatar answered Oct 10 '22 16:10

nimblegorilla


The mysql2 gem exposes an option to execute an initial command on connect and reconnect. You can set the init_command from inside database.yml:

production:   host: ...   username: ...   init_command: "SET @@SESSION.sql_mode = ''" 
like image 28
Graeme Avatar answered Oct 10 '22 15:10

Graeme