Gaurav
Gaurav

Reputation: 535

JSON Array parsing in ROR

I am getting JSON in following format from my Android application

{"list":[{"itemno":"w01","name":"t01","amount":"120","status":"done"},{"itemno":"w02","name":"t02","amount":"120","status":"done"},{"itemno":"w03","name":"t03,"amount":"120","status":"done""}]}

I need to parse this to insert into mysql table "list". I modified "create" code in my controller as below

def create
lists = params[:list].collect{|key,list_attributes| List.new(list_attributes) }
    all_list_valid = true
    lists.each_with_index do |list,index|
     unless list.valid?
      all_list_valid = false
      invalid_list = lists[index]
     end
    end

    if all_list_valid
     @lists = []
     lists.each do |list|
       list.save
       @lists << list
     end
      format.html { redirect_to @list, notice: 'List was successfully created.' }
      format.json { render json: @list, status: :created, location: @list } 
    else
      format.html { render action: "new" }
      format.json { render json: @list.errors, status: :unprocessable_entity }
    end
  end

But its unable to parse the JSON, so not calling the create method. I am very new to ROR and tried above code too from web. Not sure if the entire piece above is incorrect or I am missing something. Please advise. Thanks.

Upvotes: 3

Views: 1047

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54902

Also, you can refactor your code a little bit:

# This part of code
@lists = []
lists.each do |list|
  list.save
  @lists << list
end
# Can be shortened:
lists.map(&:save)
@lists = lists

The whole action can be refactored like this:

def create
  lists = params[:list].each{ |list_attributes| List.new(list_attributes) }
  valid, not_valid = lists.partition{ |list| list.valid? }

  if not_valid.blank?
    lists.map(&:save)
    @lists = lists
    format.html { redirect_to @list, notice: 'List was successfully created.' }
    format.json { render json: @list, status: :created, location: @list }
  else
    format.html { render action: "new" }
    format.json { render json: @list.errors, status: :unprocessable_entity }
  end
end

Upvotes: 3

Related Questions