0

I have two ActiveRecord models, CartItem and OrderItem. While CartItem is dynamic and contains associations to various other models, OrderItem is static and represents a state in the past. The two have some attributes in common, some attributes different, and some that are functions of the other. OrderItems are always only created from CartItems, so logically it seems like I should construct an OrderItem by passing a CartItem to the constructor. I know I could construct an empty OrderItem and then use a separate method to set its attributes from the CartItem, but that seems at odds with the concept. What is the appropriate way to do this?

RussK
  • 199
  • 1
  • 17

1 Answers1

0

You can define your OrderItem initialize method with an hash as argument, as proposed in Overloading initialize constructor and then pass the needed CartItems attributes within a hash to create an OrderItem.

Community
  • 1
  • 1
jethroo
  • 2,086
  • 2
  • 18
  • 30
  • When you say "pass the needed CartItems attributes within a hash" do you mean the CartItems class would need to know which attributes OrderItems considers relevant? That doesn't seem like good encapsulation. I would have thought just passing the CartItem would be appropriate, but it's not working with the same code that works with a separate method. It tells me `NoMethodError (You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.delete):' But I don't call delete and I don't see any nil objects. – RussK Sep 25 '12 at 15:15