Rails api - 为什么错误的ID发送null而不是404?

时间:2017-07-31 10:49:15

标签: ruby-on-rails routes rails-api

当我在网址中输入错误的track_id时,例如:tracks/123456

=>它按预期返回404 not found

如果我尝试的是challenge_id,这是我的其他模型之一:tracks/1/challenges/12345

=>它返回null而不是404 not found

两者的代码似乎相同,所以我找不到问题。

如果您能帮助我找到为什么我会null而不是404,请看下面的代码:

的routes.rb

 resources :tracks do
   resources :challenges do
    resources :ressources
   end 
 end

challenges_controller.rb

  def show
    render json: @challenge, include: [:ressources, :challenges_startups]
  end

  private

  def set_challenge
     @track = Track.find(params[:track_id])
     @challenge = @track.challenges.where(id: params[:id]).first
   end

tracks_controller.rb

  def show
    render json: @track, include: [:challenges]
  end

 private

 def set_track
    @track = Track.find(params[:id])
 end

rails_server

对于挑战=>错误的

Started GET "/tracks/3/challenges/20/" for 127.0.0.1 at 2017-07-31 12:24:19 +0200
  ActiveRecord::SchemaMigration Load (0.5ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ChallengesController#show as */*
  Parameters: {"track_id"=>"3", "id"=>"20"}
  Track Load (0.4ms)  SELECT  "tracks".* FROM "tracks" WHERE "tracks"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
  Challenge Load (0.3ms)  SELECT  "challenges".* FROM "challenges" WHERE "challenges"."track_id" = ? AND "challenges"."id" = ? ORDER BY "challenges"."id" ASC LIMIT ?  [["track_id", 3], ["id", 20], ["LIMIT", 1]]
  Startup Load (0.4ms)  SELECT  "startups".* FROM "startups" ORDER BY "startups"."id" ASC LIMIT ?  [["LIMIT", 1]]
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Class (0.18ms)
Completed 200 OK in 63ms (Views: 19.3ms | ActiveRecord: 2.6ms)

对于曲目

Started GET "/tracks/222" for 127.0.0.1 at 2017-07-31 12:30:37 +0200
Processing by TracksController#show as */*
  Parameters: {"id"=>"222"}
  Track Load (0.2ms)  SELECT  "tracks".* FROM "tracks" WHERE "tracks"."id" = ? LIMIT ?  [["id", 222], ["LIMIT", 1]]
  Startup Load (0.3ms)  SELECT  "startups".* FROM "startups" ORDER BY "startups"."id" ASC LIMIT ?  [["LIMIT", 1]]
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.16ms)
Completed 404 Not Found in 6ms (Views: 4.1ms | ActiveRecord: 0.5ms)

1 个答案:

答案 0 :(得分:2)

您已定义@challenge,如下所示

@challenge = @track.challenges.where(id: params[:id]).first
如果没有符合条件的记录

where会返回nil。这就是为什么你得到 null 而不是 404找不到的原因。

find相反,如果记录不存在则返回 404 not

如果您想找到 404找不到,请修改@challenge,如下所示

@challenge = @track.challenges.find(params[:id])