如何从json散列中将数据保存到数据库,json散列在rails中具有嵌套值

时间:2012-04-24 12:21:04

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.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

3 个答案:

答案 0 :(得分:0)

在模型中使用带有列名的'serialize'关键字来保存json数据。

例如:列名称为json_data,型号为

serialize :json_data

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

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

然后保存对象

答案 1 :(得分: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=nested+forms

所以在你的GuestOrder模型中应该有像:

accepts_nested_attributes_for :order_batches

在params中,order_batches属性应该包含在单独的哈希中,如下所示:

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

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

答案 2 :(得分: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