[在Rails模型中发生回滚时如何保存记录

问题描述 投票:1回答:3

我的模特看起来像这样

class Policy < ApplicationRecord
    has_many :receipts
end
class Receipt < ApplicationRecord
  belongs_to :policies
  has_many :outpatients
  has_many :hospitalizations
  has_many :surgeries
  has_many :others
end

我试图生成这样的样本数据。

2.6.3 :023 > Policy.all
  Policy Load (0.4ms)  SELECT `policies`.* FROM `policies`
 => #<ActiveRecord::Relation [#<Policy id: 1, comment: "firsts", name: "hikaru", birthdate: nil, contractdate: nil, created_at: "2019-11-19 09:58:33", updated_at: "2019-11-19 09:58:33">]> 
2.6.3 :024 > receipt
 => #<Receipt id: nil, receipt_day: "2019-11-01", policy_id: 1, created_at: nil, updated_at: nil> 
2.6.3 :025 > Receipt.all
  Receipt Load (0.2ms)  SELECT `receipts`.* FROM `receipts`
 => #<ActiveRecord::Relation []> 
2.6.3 :026 > receipt.save
   (0.2ms)  BEGIN
   (0.3ms)  ROLLBACK
 => false 
2.6.3 :027 > receipt.errors.full_messages
 => ["Policies must exist"] 

我试图保存收据数据,但是发生了一些错误,似乎存在政策,如何解决此类问题?

谢谢

ruby-on-rails activerecord ruby-on-rails-5
3个回答
3
投票

问题在这里:

belongs_to :policies

并且可以通过以下方式固定:

belongs_to :policy

[显然,:receipt属于一个:policy。从Rails文档:

belongs_to关联必须使用单数形式。如果您在上述示例中对Book模型中的author关联使用了复数形式,并尝试通过Book.create(authors:@author)创建实例,则会被告知存在一个“未初始化的常量Book :: Authors ”。https://guides.rubyonrails.org/association_basics.html#the-belongs-to-association


1
投票

belongs_to关系被定义为单数术语,因此应为:

class Receipt < ApplicationRecord
  belongs_to :policy
end

0
投票

一旦按照说明将belongs_to固定为belongs_to: policy,就可以填充数据:

p = Policy.create(comment: 'foo', name: 'bar', ...)
# now you have a policy
r = Receipt.create(policy: p, other policy parameters)
© www.soinside.com 2019 - 2024. All rights reserved.