Reputation: 197
I'm having difficulty approaching a common issue of processing orders in Rails 4. I have a model object "Offers" which are then accepted by Users. This action "accept" needs to create a new Order object which saves the same attributes as the Offer object. From what I've read my code should look as follows:
class User
has_many :offers
has_many :orders, through :offers
# ...
end
class Offer
belongs_to :user, dependent: :destroy
has_one: order
# ...
end
class Order
belongs_to :offer
def add_fields_from_offer(order)
order.offer.each do |offer|
offer_id = nil
order << offer
end
end
end
I would appreciate any advice on this code or the structure of this approach. The Offer object is really the transactional product so it should be destroyed once accepted. But I would like the order saved as an object for the User's account history.
This essentially means repeating the same fields but in a different model - is this a good approach or is there a better way?
Many thanks
Upvotes: 0
Views: 201
Reputation: 197
After some further research I found it was easier to only use a single model (here "offers") and use the state_machine gem for assistance. This is ideal if your product goes through several stages e.g. accepted, posted, etc etc.
The documentation explains how to implement this in the model e.g.
state_machine :initial => :new do
event :accept do
transition :from => :new, :to => :accepted, :unless => :expired?
end
Upvotes: 0
Reputation: 277
You can ditch the Offer
model entirely and add a boolean accepted
or is_offer
field to your Order
.
Upvotes: 1