Heisenberg
Heisenberg

Reputation: 5279

How do I save record when rollback happens in Rails Model

My model looks like this

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

I tried to generate sample data like this.

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"] 

I tried to save receipt data but some error has occured,it seems policy exist,How can I fix such issues?

Thanks

Upvotes: 1

Views: 139

Answers (3)

Yaniv Iny
Yaniv Iny

Reputation: 19

Once you fix the belongs_to as stated (to belongs_to: policy), you can do populate the data:

p = Policy.create(comment: 'foo', name: 'bar', ...)
# now you have a policy
r = Receipt.create(policy: p, other policy parameters)

Upvotes: 0

Fajri
Fajri

Reputation: 56

The problem is here:

belongs_to :policies

and can be fixed by:

belongs_to :policy

Obviously, a :receipt belongs to one :policy. From Rails documentation:

belongs_to associations must use the singular term. If you used the pluralized form in the above example for the author association in the Book model and tried to create the instance by Book.create(authors: @author), you would be told that there was an "uninitialized constant Book::Authors". https://guides.rubyonrails.org/association_basics.html#the-belongs-to-association

Upvotes: 4

Hates_
Hates_

Reputation: 68671

belongs_to relationships are defined as a singular term so should be:

class Receipt < ApplicationRecord
  belongs_to :policy
end

Upvotes: 1

Related Questions