Reputation: 141
I have troubles in my rails API with a model, my plays_cards model have some foreigns keys but with one I have troubles because I got Mysql2::Error: Field 'deck_id' doesn't have a default value
but I don't need my deck and game to be obligatory.
PS: it works in development but not in production
This is my model:
class PlayCard < ApplicationRecord
# @!group RELATIONS
belongs_to :card
belongs_to :deck, optional: true
belongs_to :game, optional: true
belongs_to :user
# @!endgroup
# @!group VALIDATORS
validates :card_id, presence: true, blank: false, nill: false
validates :user_id, presence: true, blank: false, nill: false
validates :atk, presence: true, blank: false, nill: false, numericality: { greater_than_or_equal_to: 0 }
validates :hp, presence: true, blank: false, nill: false, numericality: { greater_than: 0 }
validates :uid, presence: true, allow_blank: false, allow_nil: false, length: { is: 4 }, uniqueness: true
# @!endgroup
end
And this is my migration:
class CreatePlayCards < ActiveRecord::Migration[5.2]
def change
create_table :play_cards do |t|
t.references :card, foreign_key: true, null: false
t.integer :atk, null: false
t.integer :hp, null: false
t.references :deck, foreign_key: true
t.references :game, foreign_key: true
t.string :uid, limit: 4, null: false
t.timestamps
end
end
end
Do you have an idea ?
Have a nice day
Upvotes: 1
Views: 3875
Reputation: 437
On rails 3, just change the property of your column like this
change_column :table, :column, :integer, null: true
Upvotes: 0
Reputation: 23
There's nothing wrong with your actual Rails code as far as I can tell; I copied the relevant bits and ran it locally and it was fine. Although you do have some typos in the model you should fix (nill instead of nil). I think this is a database configuration problem, especially considering you said it works on development but not production. Googling the error message you posted Mysql2::Error: Field 'deck_id' doesn't have a default value
gives results such as this. According to one of the answers there:
This is caused by the STRICT_TRANS_TABLES SQL mode defined in the
%PROGRAMDATA%\MySQL\MySQL Server 5.6\my.ini
file. Removing that setting and restarting MySQL should fix the problem.
Upvotes: 2
Reputation: 36860
You don't need foreign_key: true
on the t.refrences
lines. They'll force referential integrity tests.
Roll back, then change the migration to...
t.references :deck
t.references :game
Alternatively you can just create the integer fields and bypass the database integrieites
t.integer :deck_id
t.integer :game_id
Upvotes: 6