【问题标题】:How do I save record when rollback happens in Rails Model在 Rails 模型中发生回滚时如何保存记录
【发布时间】:2019-11-19 10:13:05
【问题描述】:

我的模型是这样的

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


    【解决方案1】:

    问题出在这里:

    belongs_to :policies
    

    并且可以通过以下方式修复:

    belongs_to :policy
    

    显然,一个:receipt 属于一个:policy。来自 Rails 文档:

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

    【讨论】:

      【解决方案2】:

      belongs_to 关系被定义为单数,所以应该是:

      class Receipt < ApplicationRecord
        belongs_to :policy
      end
      

      【讨论】:

        【解决方案3】:

        一旦您按照说明修复了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)
        

        【讨论】:

          猜你喜欢
          • 2011-06-08
          • 1970-01-01
          • 2017-02-02
          • 2022-01-17
          • 2012-07-13
          • 2017-07-31
          • 2018-03-02
          • 1970-01-01
          • 2015-04-23
          相关资源
          最近更新 更多