简体   繁体   English

Rails-阻止发布请求从数组创建多个行,同时仍保留数据

[英]Rails - Prevent post request creating multiple rows from an array whilst still keeping the data

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. 如果您不熟悉ShopifyAPI,则只需查看订单JSON并在我的交易表中创建每个订单的内部行,此刻它仅存储订单ID,然后进入line_items数组并获取变体与其一起存储的标题。

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: 您可以创建具有以下关系的两个Models TransactionItem

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. 我认为通过这种方式,您可以在项目表中使用variant_title

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. 我对shopyify不太熟悉,但是您的问题似乎与以下事实有关:由于放置Transaction.new调用的位置,您正在为每个订单项创建一个新对象。 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 悟空的解决方案与我所指的相似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM