Rails - 如何接受JSON对象数组

Kei*_*ahn 5 json ruby-on-rails

如何在rails站点上接受一组JSON对象?我发布了类似的东西

{'team':{'name':'Titans'}}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试发布带有对象数组的JSON.它只保存第一个对象.

{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}
Run Code Online (Sandbox Code Playgroud)

我的目标是在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
Run Code Online (Sandbox Code Playgroud)

我是否接受了参数:对于每个元素,创建一个新的团队或什么?我是ruby的新手,所以任何帮助都会受到赞赏.

Sou*_*amy 2

让我假设你发帖

{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}
Run Code Online (Sandbox Code Playgroud)

那么你的参数将是

"team" => {"0"=>{"chapter_name"=>"Titans"}, "1"=>{"chapter_name"=>"Dragons"}, "2"=>{"chapter_name"=>"Falcons"}}  
Run Code Online (Sandbox Code Playgroud)

我的想法是

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 
Run Code Online (Sandbox Code Playgroud)

  • 如果您想保存所有团队或不保存任何团队,您应该将保存包装在事务中(当然,假设您的数据库支持事务)http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html (2认同)