vendredi 15 juin 2018

Rails foreign key optional don't work

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

Aucun commentaire:

Enregistrer un commentaire