2011-10-13 75 views
5

如何接受我的Rails站點上的JSON對象數組?我發佈類似Rails - 如何接受JSON對象數組

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

但是,如果我嘗試發佈JSON與對象數組。它只保存第一個對象。

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

我的目標是在1個JSON文件中發送多個「團隊」。我必須在Rails方面寫什麼?

在鐵軌邊,我有一些像

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 

時候我的PARAMS:對於每個元素,創建一個新的團隊還是什麼?我是新來的紅寶石,所以任何幫助將不勝感激。

回答

2

讓我假設你發佈

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

然後你PARAMS將

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

我的想法是

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

如果你想要麼保存所有團隊或沒有,你應該換保存在一個事務內部(當然,假設你的數據庫支持事務)http://api.rubyonrails.org/classes/ActiveRecord/Transactions /ClassMethods.html –

+0

實際上我不知道有關交易的事情。感謝您介紹有關交易的有用指南。 –