首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails -如何接受JSON对象数组

Rails -如何接受JSON对象数组
EN

Stack Overflow用户
提问于 2011-10-13 18:49:11
回答 1查看 6.3K关注 0票数 5

如何在我的rails站点上接受JSON对象数组?我发布了类似这样的内容

代码语言:javascript
运行
复制
{'team':{'name':'Titans'}}

但是,如果我试图发布一个包含对象数组的JSON。它只保存第一个对象。

代码语言:javascript
运行
复制
{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}

我的目标是在一个JSON文件中发送多个‘团队’。在Rails端我应该写些什么?

在rails方面,我有一些类似的东西

代码语言:javascript
运行
复制
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

我是否需要参数:并为每个元素创建一个新的团队或其他什么?我刚接触ruby,所以如果有任何帮助,我将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-13 21:41:44

让我假设你发布了

代码语言:javascript
运行
复制
{'team':[{'name':'Titans'},{'name':'Dragons'},{'name':'Falcons'}]}

那么你的助手将会是

代码语言:javascript
运行
复制
"team" => {"0"=>{"chapter_name"=>"Titans"}, "1"=>{"chapter_name"=>"Dragons"}, "2"=>{"chapter_name"=>"Falcons"}}  

我的想法是

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7752971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档