문제

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

도움이 되었습니까?

해결책 2

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

다른 팁

You can ditch the Offer model entirely and add a boolean accepted or is_offer field to your Order.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top