2011-10-13 17 views
5

मैं अपनी रेल साइट पर JSON ऑब्जेक्ट्स की सरणी कैसे स्वीकार करूं? मैं कुछ पोस्ट करता हूं जैसेरेल - JSON ऑब्जेक्ट्स की एक सरणी को कैसे स्वीकार करें

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

हालांकि, अगर मैं वस्तुओं की एक सरणी के साथ JSON पोस्ट करने का प्रयास करता हूं। यह केवल पहली वस्तु बचाता है।

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

मेरा लक्ष्य 1 JSON फ़ाइल में एकाधिक 'टीम' भेजना है। मुझे रेल की तरफ क्या लिखना है?

रेल तरफ, मैं की तरह

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 

कुछ मैं पैरामीटर लेने के क्या है: और प्रत्येक तत्व के लिए, एक नई टीम या कुछ बनाना? मैं रूबी के लिए नया हूँ इसलिए किसी भी मदद की सराहना की जाएगी।

उत्तर

2

अपने पैरामीटर हो जाएगा मुझे आप पोस्ट

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

तो मान लेते हैं

"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

वास्तव में मुझे अभी तक लेनदेन के बारे में पता नहीं है। लेनदेन के बारे में ऐसी उपयोगी मार्गदर्शिका शुरू करने के लिए धन्यवाद। –

संबंधित मुद्दे