错误Rails 5 <class>必须存在

时间:2017-10-18 14:17:58

标签: ruby-on-rails database factory-bot

这种交付模式的创建应该在附加到用户后才能工作......

class Delivery < ApplicationRecord
  enum kind_of: { package: 0, facturation: 1 }
  belongs_to :sender, class_name: 'User'
  has_many :orders, foreign_key: "package_delivery_id"
  has_many :invoices, foreign_key: "invoices_delivery_id"
  has_one :address
  has_many :runs, dependent: :destroy
  accepts_nested_attributes_for :address
end

......但是,在我的规范中

require 'rails_helper'

describe OrderPolicy do
  context 'toegang' do
    subject { OrderPolicy.new(user, order) }
    let(:user) { create :user }
    let(:delivery) { create :delivery, sender: user }
    let(:order) { create :order, customer: user, status: 'open', package_delivery: delivery }
    let!(:selection) { create( :selection, :product_name         => 'Honingpot',
                                           :product_quantity     => 4,
                                           :product_price        => '5,00',
                                           :product_mail_weight  => '460',
                                           :product_sales_tax    => 6,
                                           :order                => order) }

...

还有这一个:

require 'rails_helper'

describe DeliveryPolicy do
  context 'toegang' do
    subject { DeliveryPolicy.new(user, delivery) }
    let(:user) { create :user }
    let(:delivery) { FactoryGirl.create :delivery }

...

...我收到错误:

交付必须存在

虽然我有那里的用户。 (optional: true也没有用,顺便说一下。)

奇怪的是,我需要在控制台中让Delivery.create开始工作才能加入sender: ...

1 个答案:

答案 0 :(得分:0)

&#34;这种交付模式的创建应该在附加到用户之后才能工作......&#34; - 那就是问题所在?然后你可以这样做:

class Delivery < ApplicationRecord
  enum kind_of: { package: 0, facturation: 1 }
  belongs_to :sender, class_name: 'User', required: false

自Rails5起,belongs_to默认添加required: true