我有一个具有多个属性的产品模型(customer_type
,customer_name
,dept_type
等......)我正试图用一些数据来播种它。
我在db/seeds.rb
文件中有以下内容
Product.create(customer_type:'Retailer', customer_name: 'Walmart', dept_type: 'Grocery')
我保存文件然后运行rake db:Seed
我没有收到任何错误消息但是当我加载我的应用程序时,没有数据存在?我在这做错了什么?
每次它都没有返回错误信息但是数据没有加载时我也尝试了rake db:setup
和rake db:reset
。
更新我修改了我的db种子文件,看起来像这样
Product.create!(customer_type:'Retailer', customer_name: 'Walmart', dept_type: 'Grocery')
当我运行rake db:reset我得到错误“验证失败:客户类型不包含在列表中”
我的产品模型文件带有验证
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
我尝试使用客户类型值Retailer和制造商没有运气来播种数据库
您的模型很可能无法保存。你忽略了create
调用中的任何错误。请改用Product.create!
,如果您的创建失败,则会引发异常。
我认为问题在于你的语法。请试试
validates : customer_type, :inclusion => { :in => CUSTOMER_TYPES }
,它会工作正常。
如果我是你,我会在这种情况下使用enums
。使用Enums
完美地绑定列。