无法使用belongs_to关系创建新的Activerecord

时间:2017-05-29 21:17:06

标签: ruby-on-rails ruby activerecord

我是Ruby on Rails的初学者,我正在尝试创建一个seed.rb文件来填充我的数据库。

但是我在创建新的Request记录时遇到了问题。

这是我的种子档案:

if Rails.env == "development" || Rails.env == "test"

  avaya = Company.create!(name: "Avaya")
  microsoft = Company.create!(name: "Microsoft")
  bradesco = Company.create!(name: "Bradesco")

  customer = Customer.create!(name: "Leon Schmidt", email: "leon.schmidt@avaya.com", company_id: avaya.id)
  Customer.create!(name: "Teri Wright", email: "teri.wright@avaya.com", company_id: avaya.id)
  Customer.create!(name: "Jasmine Bush", email: "jasmine.bush@microsoft.com", company_id: microsoft.id)
  Customer.create!(name: "Jake Blair", email: "jake.blair@bradesco.com.br", company_id: bradesco.id)

  rate = Rate.create!(rate: 0.0165, days: 10, default_rate: true)

  Request.create!(title_value: 1500, term: 28, monthly_revenue: 75000, receivable_value: 1425.75, rate_id: rate.id, customer_id: customer.id)

elsif Rails.env == "production"

  Rate.create(rate: 0.0165, days: 10, default_rate: true)

end

每当我运行rake db:reset以重新填充开发数据库时,我都会收到此错误:

rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Customers must exist
c:/Desenvolvimento/Coding Tests/FactoringRateCalculator/db/seeds.rb:23:in `<top (required)>'
Tasks: TOP => db:reset => db:setup => db:seed

请注意,第23行是:Request.create!(title_value: 1500, term: 28, monthly_revenue: 75000, receivable_value: 1425.75, rate_id: rate.id, customer_id: customer.id)

我的模特如下:

class Customer < ApplicationRecord
  belongs_to :company
  has_many :requests

  validates_associated :requests
  validates :name, presence: true
  validates :email, presence: true, email: true
end

class Request < ApplicationRecord
  belongs_to :customers, required: true
  belongs_to :rate, required: true

  validates :term, presence: true, numericality: { greater_than_or_equal_to: 10 }
  validates :title_value, presence: true, numericality: { greater_than_or_equal_to: 500 }
  validates :monthly_revenue, :receivable_value, presence: true, numericality: true
end

class Rate < ApplicationRecord
  has_many :requests
  validates_associated :requests

  validates :rate, numericality: true, presence: true
  validates :days, numericality: { greater_than_or_equal_to: 10 }, presence: true
  validates :rate, :days, :default_rate, presence: true
end

class Company < ApplicationRecord
  has_many :customers

  validates_associated :customers
  validates :name, presence: true
end

我正在使用Ruby 2.3和Rails 5.1。

1 个答案:

答案 0 :(得分:1)

您的required验证是使用您的模型的复数版本指定的:

belongs_to :customers, required: true

尝试使用单数方式:

belongs_to :customer, required: true

这就是为什么错误显示“Customers”"ActiveRecord::RecordInvalid: Validation failed: Customers must exist",因为您的种子是根据您指定的关系制作的。