2011-10-13 43 views
5

Làm cách nào để chấp nhận một mảng đối tượng JSON trên trang web đường ray của tôi? Tôi đăng một cái gì đó nhưĐường ray - Cách chấp nhận một mảng đối tượng JSON

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

Tuy nhiên, nếu tôi cố gắng đăng một JSON với một loạt các đối tượng. Nó chỉ lưu đối tượng thứ nhất.

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

Mục tiêu của tôi là gửi nhiều 'nhóm' trong 1 tệp JSON. Tôi phải viết gì ở bên Rails?

Về phía đường ray, tôi có cái gì đó như

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 

Tôi lấy params: và cho mỗi phần tử, tạo ra một nhóm mới hoặc một cái gì đó? Tôi mới đến ruby ​​vì vậy bất kỳ trợ giúp sẽ được đánh giá cao.

Trả lời

2

Hãy để tôi giả sử bạn gửi

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

Sau đó params của bạn sẽ được

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

Ý tưởng của tôi là

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

Nếu bạn muốn thể lưu tất cả các đội hay không, bạn nên quấn tiết kiệm bên trong một giao dịch (giả sử DB của bạn hỗ trợ các giao dịch, tất nhiên) http://api.rubyonrails.org/classes/ActiveRecord/Transactions /ClassMethods.html –

+0

thực sự tôi chưa biết về giao dịch. Cảm ơn bạn đã giới thiệu một hướng dẫn hữu ích về giao dịch. –

Các vấn đề liên quan