Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

How do I accept an array of JSON objects on my rails site? I post something like

{'team':{'name':'Titans'}}

However, if I try to post a JSON with an array of objects. It only saves the 1st object.

{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}

My goal is to send multiple 'teams' in 1 JSON file. What do I have to write on the Rails side?

On the rails side, I have something like

def create
  @team = Team.new(params[:team])
  @team.user_id = current_user.id

  respond_to do |format|
    if @team.save
      format.html { redirect_to(@team, :notice => 'Team was successfully created.') }
      format.json  { render :json => @team, :status => :created, :location => @team }
    else
      format.html { render :action => "new" }
      format.json  { render :json => @team.errors, :status => :unprocessable_entity }
    end
  end
end

Do I take the params: and for each element, create a new team or something? I'm new to ruby so any help would be appreciated.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Let me assume you post

{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}

Then your params will be

"team" => {"0"=>{"chapter_name"=>"Titans"}, "1"=>{"chapter_name"=>"Dragons"}, "2"=>{"chapter_name"=>"Falcons"}}  

My idea is

def create
  #insert user id in all team
  params[:team].each_value { |team_attributes| team_attributes.store("user_id",current_user.id) }
  #create instance for all team
  teams = params[:team].collect {|key,team_attributes| Team.new(team_attributes) }
  all_team_valid = true
  teams.each_with_index do |team,index|
    unless team.valid?
      all_team_valid = false
      invalid_team = teams[index]
    end 
  end 

  if all_team_valid
    @teams = []
    teams.each do |team|
      team.save
      @teams << team
    end 
    format.html { redirect_to(@teams, :notice => 'Teams was successfully created.') }
    format.json  { render :json => @teams, :status => :created, :location => @teams }
  else
    format.html { render :action => "new" }
    format.json  { render :json => invalid_team.errors, :status => :unprocessable_entity }
  end 

end 
share|improve this answer
1  
If you want to either save all teams or none you should wrap the saves inside a transaction (assuming your DB supports transactions, of course) api.rubyonrails.org/classes/ActiveRecord/Transactions/… –  Wizard of Ogz Oct 13 '11 at 14:38
    
actually i don't know about transactions yet.thank you for introducing such a useful guide about transactions. –  soundar Oct 13 '11 at 14:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.