2017-05-29 51 views
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。

回答

1

required驗證與模型的複數形式規定:

belongs_to :customers, required: true 

嘗試使用奇異方式:

belongs_to :customer, required: true 

這就是爲什麼錯誤說「客戶」"ActiveRecord::RecordInvalid: Validation failed: Customers must exist",因爲你的種子是按照你指定的關係製造的。

+0

是的,你是對的!我將'客戶'改爲'客戶',它工作。謝謝您的幫助! – Felipe

+0

不客氣!我會更新答案。 –

相關問題