【问题标题】:Validation Errors Seeding Rails 3 w Seeds.rb验证错误播种 Rails 3 w Seeds.rb
【发布时间】:2014-02-25 01:31:53
【问题描述】:

我有一个具有多个属性(customer_typecustomer_namedept_type 等)的 Products 模型,我正在尝试用一些数据为其植入。

我的db/seeds.rb 文件中有以下内容

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

我保存文件然后运行rake db:Seed 我没有收到错误消息但是当我加载我的应用程序时没有数据存在?我在这里做错了什么?

我也尝试过rake db:setuprake db:reset,每次它都没有返回错误消息但没有加载数据。

更新 我修改了我的数据库种子文件看起来像这样

  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

我已经尝试使用客户类型值零售商和制造商来播种数据库,但运气不好

【问题讨论】:

  • 请在您的Product 模型中向我们展示您的验证。
  • @nathanvda CUSTOMER_TYPES = ["Retailer", "Manufacturer"] 验证:customer_type,包含:CUSTOMER_TYPES

标签: ruby-on-rails seeding


【解决方案1】:

您的模型可能无法保存。您忽略了来自 create 调用的任何错误。请改用Product.create!,如果创建失败,则会引发异常。

【讨论】:

  • 谢谢,我现在收到一个错误,即不包括 customer_type。这是我的模型中的必填字段,设置为 CUSTOMER_TYPES 选择列表我在 db 种子文件中输入了选择选项之一,但似乎没有。知道我做错了什么吗?
【解决方案2】:

我认为问题出在您的语法上。 请尝试

validates : customer_type, :inclusion =&gt; { :in =&gt; CUSTOMER_TYPES } 它将正常工作。

如果我是你,我会在这种情况下使用 enums。使用Enums 完美绑定列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多