0

I have a model

class Card < ActiveRecord::Base
  belongs_to :CardColour
  validates :CardColour, presence:true

In the console I type

@a = Card.new(:card_colour_id =1)

However it is not valid. I ask why, by doing @a.errors, and the console tells me

=> #<ActiveModel::Errors:0x000000052e57e8 @base=#<Card id: nil, card_colour_id: 1>, @messages={:CardColour=>["can't be blank"]}> 

I've spent hours looking at this, am completely baffled and am at my wits end as to why I can't seemingly do the most simple things in Rails.

I've looked up questions with similar titles, but they all seem to be more complicated scenarios. I have more going on than this example, but nothing more complicated. eg I actually have 3 foreign keys set up, and they all tell me they can't be blank, even if they are populated with valid values.

I have found this answer which suggests my code is correct, and will actually do what I want it to (ie validate that the card_colour_id links to an actual object in the CardColour model).

Community
  • 1
  • 1
reedstonefood
  • 131
  • 2
  • 15

2 Answers2

1

You are validating CardColour, but in your console you create a new Card with card_colour_id, but not with CardColour. That is why you get an error.

You should change validates :CardColour, presence :true to validates :your_model's_column, presence :true

Alex Zakruzhetskyi
  • 1,383
  • 2
  • 22
  • 43
  • This works! Thanks! But it seems it will accept any integer as card_colour_id? I thought belongs_to set up a foreign key relationship? – reedstonefood Jun 18 '16 at 22:09
0

Please change your model code to

class Card < ActiveRecord::Base
  belongs_to :card_colour
  validates :card_colour_id, presence:true

and your new card line to

@a = Card.new(:card_colour_id => 1)

or with the new syntax

@a = Card.new(card_colour_id: 1)
Sebin
  • 1,044
  • 1
  • 8
  • 21