1

从数据库 to_json 渲染数据效果很好

def getOrderDetails
    #To get the details of a particular guest_order and its batches and items
    @guest_order = GuestOrder.find(params[:id])
    render json: @guest_order.to_json(except: [:created_at, :updated_at], 
            include: {order_batches: {except: [:guest_order_id, :created_at, :updated_at], 
            include: {order_items: {except: [:order_batch_id, :created_at, :updated_at] } }
                }
              }
            )
  end

但是,如何将相同表的数据保存到数据库中。参数是

Parameters: {"guestOrder"=>"{\"GuestOrder\"{\"GuestOrderId\":1,
\"orderTime\":\"2012-04-25 18:28:30\",\"notes\":\"spicy\",\"userId\":14,\"tableId\":1,
\"batch\":[{\"items\":[{\"itemId\":1,\"quantity\":4,\"dishId\":1},
{\"itemId\":2,\"quantity\":4,\"dishId\":3},
{\"itemId\":3,\"quantity\":3,\"dishId\":6}],
\"placed\":\"2012-04-25 18:28:30\",\"batchId\":1}],
\"numberOfAdults\":1,\"numberOfChilderns\":3}}"} 

我已经像这样解析了参数值,

def guestOrder
    guest_order = JSON.parse(params["guestOrder"])
    # How to store the values from guest_order to database tables
end

    1.9.2p290 :002 > guestOrder = JSON.parse("{\"GuestOrder\"{\"GuestOrderId\":1,
\"orderTime\":\"2012-04-25 18:28:30\",\"notes\":\"spicy\",\"userId\":14,\"tableId\":1,
\"batch\":[{\"items\":[{\"itemId\":1,\"quantity\":4,\"dishId\":1},
{\"itemId\":2,\"quantity\":4,\"dishId\":3},
{\"itemId\":3,\"quantity\":3,\"dishId\":6}],
\"placed\":\"2012-04-25 18:28:30\",\"batchId\":1}],
\"numberOfAdults\":1,\"numberOfChilderns\":3}}")


 => {"GuestOrder"=>{"GuestOrderId"=>1, "orderTime"=>"2012-04-25 18:28:30", "notes"=>"spicy", 
"userId"=>14, "tableId"=>1, "batch"=>[{"items"=>[{"itemId"=>1, "quantity"=>4, "dishId"=>1}, 
{"itemId"=>2, "quantity"=>4, "dishId"=>3}, {"itemId"=>3, "quantity"=>3, "dishId"=>6}], 
"placed"=>"2012-04-25 18:28:30", "batchId"=>1}], "numberOfAdults"=>1, 
"numberOfChilderns"=>3}} 

这里guest_orders有很多order_batches,order_batches有很多order_items

# == Schema Information
#
# Table name: guest_orders
#
#  GuestOrderId   :integer         not null, primary key
#  adults         :integer
#  children       :integer
#  orderTime      :datetime
#  tableId        :integer
#
# Table name: order_batches
#
#  batchId        :integer         not null, primary key
#  placed         :datetime
#  guest_order_id :integer
#
# Table name: order_items
#
#  itemId         :integer         not null, primary key
#  quantity       :integer
#  dishId         :integer
#  order_batch_id :integer
4

3 回答 3

0
  def guestOrder
    guest_order = JSON.parse(params["guestOrder"])["GuestOrder"]
    placed_at = Time.zone.parse(guest_order["orderTime"])
    @order = GuestOrder.new(placed: placed_at, guest_table_id: guest_order["tableId"], user_id: guest_order["userId"], 
            adults: guest_order["numberOfAdults"], children: guest_order["numberOfChilderns"], notes: guest_order["notes"])
    guest_order["batch"].each do |batch|
      placed = Time.zone.parse(batch["placed"])
      @batch = OrderBatch.new(placed: placed)
      batch["items"].each do |item| 
        @batch.order_items << OrderItem.new(dish_id: item["dishId"], quantity: item["quantity"]) 
      end 
      @batch.guest_order = @order
      @batch.save 
    end
    if @order.save 
      render json: @order.to_json(only: [:id], message: "success") 
    else 
      render json: @order.errors 
    end  
  end
于 2012-04-26T08:19:53.857 回答
0

在模型中使用带有列名的“序列化”关键字来保存 json 数据。

例如:列名是json_data,在模型中

serialize :json_data

然后在你的控制器中使用,

@model_obj.json_data = {:company => { :name => "IBM", :place => "US" }, :employee => {:name => "Mohan", :address => "US"}}

然后保存对象

于 2012-04-24T13:25:33.893 回答
0

你绝对应该看看accept_nested_attributes_for ActiveRecord 方法 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html还有一些关于它的Railscasts:http ://railscasts.com/episodes?utf8 =%E2%9C%93&search=嵌套+表格

所以在你的 GuestOrder 模型中应该有这样的东西:

accepts_nested_attributes_for :order_batches

在您的参数中, order_batches 属性应包含在单独的哈希中,如下所示:

"order_batches_attributes" => {"0" => {"placed" => "false"}, "1" => {"placed" => "true"}}

如果属性有效,order_batches 将使用正确的 GuestOrderId 自动保存在 db 中。

于 2012-04-24T13:28:40.163 回答