[英]How to alter params method to accept a JSON array in rails controller?
[英]Rails - How to accept an array of JSON objects
如何在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的新手,所以任何幫助都會受到贊賞。
我假設你發帖
{'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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.