Rails 4 - 嵌套资源 - REST API呈现json错误

时间:2014-07-07 18:53:48

标签: ruby-on-rails json rest

我有这些路线:

resources :championships do resources :rounds do resources :games end end

当我尝试通过POST插入游戏时出现此错误:

NoMethodError in GamesController#create undefined method 'games' for nil:NilClass

但数据插入正确!

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:我使用相同的逻辑在锦标赛中包含Rounds并没有问题

1 个答案:

答案 0 :(得分:0)

正如评论中所见,此问题来自location: @round

Rails documentation所述,location参数设置了 HTTP位置标题

需要网址作为值。如果你的 round 路由没有被命名空间或嵌套,如果你改变它来使用rails url helpers location: round_url(@round),它应该可以工作。