[英]Rails 4 - Nested resources - REST API render json error
I have these routes: 我有以下路线:
resources :championships do resources :rounds do resources :games end end
When I try to insert a game by POST I got this error: 当我尝试通过POST插入游戏时,出现以下错误:
NoMethodError in GamesController#create undefined method 'games' for nil:NilClass
But the data is inserted correctly! 但是数据已正确插入!
Part of GamesController: GamesController的一部分:
before_filter :load_round
def create
@game = @round.new(model_params)
if @game.save
render json: @game, status: :created, location: @round
else
render json: @game.errors, status: :unprocessable_entity
end
end
private
def model_params
params.require(:game).permit(:team_1_id, :team_2_id)
end
def load_round
@round = Round.find(params[:round_id])
end
PS: I am using the same logic to include Rounds inside a Championship whith no problem PS:我使用相同的逻辑将回合包括在冠军之中,没问题
As seen in comment, the issue here comes from the location: @round
. 如评论所示,这里的问题来自
location: @round
。
As stated in the Rails documentation , the location
param sets the HTTP Location header . 如Rails文档中所述,
location
参数设置HTTP Location标头 。
It takes an URL as value. 它以URL作为值。 It should work if you change this to use the rails url helpers
location: round_url(@round)
, if your round route is not namespaced or nested. 如果您将往返路由未命名空间或嵌套,则将其更改为使用rails url helper
location: round_url(@round)
应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.