Reputation: 2036
Booking -< Orders -< Transactions
class Booking < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :booking
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :order
end
I need to be able to create a Transaction
without an Order
or Booking
existing.
I'm trying to achieve the following:
When a Transaction
is created an Order
and a Booking
is automatically created. The transaction form can take a Booking.booking_number
which will be saved to the above automatically created Booking
.
I'm very new to rails and have tried a combination of accepts_nested_attributes_for
, Ryan Bates' nested model form part1 screencast and form_fields_for
without success.
Some guidance, not necessarily code, would be much appreciated.
My routes look like:
Upvotes: 0
Views: 183
Reputation: 76784
I need to be able to create a Transaction without an Order or Booking existing.
Bad system design - surely a transaction would follow an order or booking?
From your question, I'd highly recommend creating a booking or order first. This will allow you to create a transaction as a bolt-on to the order
or booking
:
#app/controllers/bookings_controller.rb
Class BookingsController < ApplicationController
def create
booking = Booking.new(booking_params)
booking.save
end
end
#app/models/booking.rb
Class Booking < ActiveRecord::Base
before_create :build_transaction #-> creates a blank transaction which can be populated later
end
Nonetheless, there's nothing stopping you creating a transaction & assigning an order later
You can do this:
#app/controllers/transactions_controller.rb
def create
Transaction.new(transaction_params)
end
#app/models/transaction.rb
Class Transaction < ActiveRecord::Base
after_create :order
def order
self.order.create!([order_details?])
end
end
If you tell me some more about what you're building, I'll be able to create a more refined response!
Upvotes: 1
Reputation: 161
Try this it may be work.
In your model
accepts_nested_attributes_for :order, :allow_destroy => true
change whether true/false depending on your form
Upvotes: 0