I'll start with my controllers create action:
def create
this_order = params[:line_items]
this_order.each do |this|
@order = Transaction.new
@order.shopifyid = params[:id]
@order.vartitle = this['variant_title']
@order.save
end
end
If you're unfamiliar with the ShopifyAPI, this is just looking through an order JSON and creating an internal row of each order in my transactions table, at the moment it just stores the order id and then goes into a line_items array and gets the variant title to store with it.
It works fine, but of course this creates a new row for each item in an order, when i actually want it to give me one order with all the items in it.
Is this a case of converting my table columns into an array of hashes? Or am i missing another way to do this?
You can create two Models Transaction
and Item
with the following relations:
Transaction
has_many :items
Item
belongs_to :transaction
Your controller action:
def create
@order = Transaction.new
@order.shopifyid = params[:id]
this_order = params[:line_items]
this_order.each do |this|
@order.items.new( #Item attributes )
end
@order.save
end
I think in this way you can have variant_title
in the item table.
I am not very familiar with shopyify but it seems like your issue is just related to the fact that you are creating a new object per line item as a result of where you are placing you Transaction.new call. Another way to organize this is just to have another table for line items. You could store this hash of line items in the database but chances are you are going to want to do some sort of queries based off of the line items and to go through the process of serializing this column for every transaction is not a time efficient solution. Goku's solution is along the lines of what I am referring to
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.