【问题标题】:Rails 4 - Nested resources - REST API render json errorRails 4 - 嵌套资源 - REST API 呈现 json 错误
【发布时间】:2014-07-07 18:53:48
【问题描述】:

我有这些路线:

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

【问题讨论】:

  • 您使用任何序列化程序吗?如果删除 location: @round 会发生什么?
  • @DimitriJorge 我删除了位置,它工作正常!这个位置有什么用?

标签: ruby-on-rails json rest


【解决方案1】:

正如评论中看到的,这里的问题来自location: @round

Rails documentation 中所述,location 参数设置 HTTP Location 标头

它需要一个 URL 作为值。如果您将其更改为使用 rails url helpers location: round_url(@round),它应该可以工作,如果您的 round 路由没有命名空间或嵌套。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2014-04-07
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多