E
E
eldar_web2017-03-21 20:57:35
Ruby on Rails
eldar_web, 2017-03-21 20:57:35

What is the correct way to use model.build_model (fallbacks) in Ruby on Rails?

Suppose there are models:
Subscriber
Address
Number
Such a relationship they have:
Subscriber->Address->Phone
Subscriber->Number
This means that Address contains subsriber_id
A Number address_id, and subscriber_id.
I want to use .buld_association when adding records so that a rollback occurs in case of an unsuccessful situation.
So:
subs = Subscriber.create
subs.build_address
And with subs.save, as I understand it, the address.subscriber_id will automatically be assigned the subscriber-a id.
And here is the main question: what if you want numbers to store both address_id and subsriber_id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2017-03-22
@Dem1

Rollbacks = Transactions .
But why do you need to additionally store the subscriber_id in the Number, if you can get the subscriber through the address, I don’t understand)

ActiveRecord::Base.transaction do
  subscriber = Subscriber.create
  address = Address.create(subscriber: subscriber)
  Number.create(subscriber: subscriber, address: address)
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question