Renegade
Renegade

Reputation: 233

Validation Errors Seeding Rails 3 w Seeds.rb

I have a Products model with several attributes (customer_type, customer_name, dept_type etc...) and I'm trying to seed it with some data.

I have the following in my db/seeds.rb file

 Product.create(customer_type:'Retailer', customer_name: 'Walmart', dept_type: 'Grocery')

I save the file then run rake db:Seed I get no error messages but when I load my app none of the data is present? what am i doing wrong here?

I also tried rake db:setup and rake db:reset each time it returns no error message but the data doesn't load.

Update I modified my db seeds file to look like this

  Product.create!(customer_type:'Retailer', customer_name: 'Walmart', dept_type: 'Grocery')

when i run rake db:reset i get error "Validation failed: Customer type is not included in the list"

My Products Model file with validations

 class Product < ActiveRecord::Base
   attr_accessible  :customer_type

   has_many :line_items
   has_many :orders, through: :line_items

   CUSTOMER_TYPES = ["Retailer", "Manufacturer"]
   validates :customer_type, inclusion: CUSTOMER_TYPES

I have tried seeding the db with both customer type values Retailer and Manufacturer no luck

Upvotes: 2

Views: 820

Answers (2)

usama
usama

Reputation: 76

I think the problem is with your syntax. Please try

validates : customer_type, :inclusion => { :in => CUSTOMER_TYPES } and it will work fine.

If I were you, I would be using enums for this type of scenario. Using Enums perfectly binds the column.

Upvotes: 0

user229044
user229044

Reputation: 239301

It's likely that your model is failing to save. You're ignoring any errors from the create call. Use Product.create! instead, and if your creation fails, it will raise an exception.

Upvotes: 8

Related Questions