1
我是Ruby on Rails的初學者,我嘗試創建一個seed.rb文件來填充我的數據庫。無法使用belongs_to關係創建新的Activerecord
但是,我在創建新的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: "[email protected]", company_id: avaya.id)
Customer.create!(name: "Teri Wright", email: "[email protected]", company_id: avaya.id)
Customer.create!(name: "Jasmine Bush", email: "[email protected]", company_id: microsoft.id)
Customer.create!(name: "Jake Blair", email: "[email protected]", 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 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。
是的,你是對的!我將'客戶'改爲'客戶',它工作。謝謝您的幫助! – Felipe
不客氣!我會更新答案。 –