2011-10-13 11 views
5

Come si accetta un array di oggetti JSON sul mio sito di binari? Inserisco qualcosa comeRails - Come accettare un array di oggetti JSON

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

Tuttavia, se provo a pubblicare un JSON con una matrice di oggetti. Salva solo il primo oggetto.

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

Il mio obiettivo è quello di inviare più 'squadre' in 1 di file JSON. Cosa devo scrivere sul lato Rails?

Sul lato rotaie, ho qualcosa di simile

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 

devo prendere il params: e per ogni elemento, creare un nuovo team o qualcosa del genere? Sono nuovo di rubino quindi qualsiasi aiuto sarebbe apprezzato.

risposta

2

Lascia che presumo si posta

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

Allora i vostri params saranno

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

La mia idea è

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 
+2

Se si desidera sia conservare tutte le squadre o nessuno si dovrebbe avvolgere il salvataggio all'interno di una transazione (presupponendo che il DB supporti le transazioni, ovviamente) http://api.rubyonrails.org/classes/ActiveRecord/Transactions /ClassMethods.html –

+0

attualmente non so ancora nulla sulle transazioni. Grazie per aver introdotto una guida così utile sulle transazioni. –

Problemi correlati