【问题标题】:Rails - How to accept an array of JSON objectsRails - 如何接受 JSON 对象数组
【发布时间】:2011-10-13 10:49:10
【问题描述】:

如何在我的 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

我是否接受参数:并为每个元素创建一个新团队或其他什么?我是 ruby​​ 新手,因此我们将不胜感激。

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    假设你发帖

    {'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 
    

    【讨论】:

    猜你喜欢
    • 2021-07-15
    • 2019-07-28
    • 2020-12-20
    • 2019-05-15
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多