Marty
Marty

Reputation: 2224

Seeding fails: "field can't be blank" but I'm seeding with a value

I have a required field for the Article table:

t.string  :article_type, null: false

And in the model:

validates :article_type,  presence: true
enum article_type:        [ :type1, :type2, :type3, :type4, :type5 ]

In my seeds I have:

books = Book.all
books.each do |book|
  title = Faker::Lorem.sentence(3)
  article_type = ["type1", "type2", "type3", "type4", "type5"].sample
  book.articles.create!( title: title,
                         article_type: article_type )
end

Problem: The create line produces the error: ActiveRecord::RecordInvalid: Validation failed: Article type can't be blank. What could be causing this? (I can confirm that the .sample line works and picks one of the five types)

Update: If I change article_type from string to integer, it works. What should I do? Because it isn't really an integer, is it...?

Upvotes: 2

Views: 435

Answers (2)

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

Try and isolate the error. See if this seeds without any issues maybe then keep segmenting?

article_type = "type1"
book.articles.create!( title: title,
                         article_type: article_type )

Upvotes: 0

Vasfed
Vasfed

Reputation: 18464

Rails enum expects corresponding db column to be integer, but yours is a string.

So either change to integer or substitute enum with value validation.

Upvotes: 1

Related Questions