Reputation: 1203
I've searched and searched, I thought I had it conquered but this problem is still giving me grief.
I have 2 models LineItems and Orders. LineItems get added into a Cart model, this is a shopping cart. LineItems are temporary in the fact that I only want them in the cart until the user checks out and pays. Since the LineItems are temporary I want to pass most of the attributes from the LineItem to a New Order when the check out occurs. How do I do this if the LineItem attributes are named differently than Order attributes and I only want to pass some of the parameters?
I'm also not sure what relationship would be best.
Thanks for the help!
Using rails 4.0 and ruby 2.0
Upvotes: 0
Views: 593
Reputation: 23268
I believe relations won't work here. As you mentioned LineItem is temporary. So, any relation will be useless, as soon as the record will be deleted from LineItem, you won't be able to access from Orders.
So, you questions boils down to: "How to copy some parameters from one model to another model".
I think the most straightforward way would be to do the following:
@order.assign_attributes(:attr1 => @lineitem.attr2, :attr2 => @lineitem.attr3)
If you have really big number of attributes, you can create a hash which will map names of attributes in @lineitem and @order. It will be something like
@mapping = { "attr1" => "attr2", "attr3" => "attr4" }
@mapping.each { |lineitem_attr_name, order_attr_name|
@order.send("#{order_attr_name}=".to_sym, lineitem_attr_name.send(lineitem_attr_name.to_sym))
}
Upvotes: 2