respond_with没有识别传递的对象?

时间:2016-04-17 17:30:22

标签: ruby-on-rails ruby-on-rails-4

Rails 4.2.6

路线:

scope module: 'v1', defaults: { format: :json } do
  resources :blog_posts, except: [:new, :edit] do
    resources :comments, only: :create
  end
end

评论控制员:

class V1::CommentsController < ApplicationController
  before_action :set_blog_post

  def create
    comment = @blog_post.comments.new(comments_params)
    comment.user = current_user
    comment.save
    respond_with(comment)
  end
end

为什么respond_with方法没有响应comment对象?

日志:

Started POST "/blog_posts/1/comments" for ::1 at 2016-04-17 23:26:43 +0600
  ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by V1::CommentsController#create as JSON
  Parameters: {"comment"=>{"message"=>"foobar"}, "blog_post_id"=>"1"}
  User Load (0.9ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? LIMIT 1  [["email", "test@test.com"]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  UPDATE "users" SET "current_sign_in_at" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["current_sign_in_at", "2016-04-17 17:26:44.221258"], ["sign_in_count", 2], ["updated_at", "2016-04-17 17:26:44.222139"], ["id", 1]]
   (0.7ms)  commit transaction
  BlogPost Load (0.4ms)  SELECT  "blog_posts".* FROM "blog_posts" WHERE "blog_posts"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (1.5ms)  INSERT INTO "comments" ("message", "blog_post_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["message", "foobar"], ["blog_post_id", 1], ["user_id", 1], ["created_at", "2016-04-17 17:26:44.259405"], ["updated_at", "2016-04-17 17:26:44.259405"]]
   (0.7ms)  commit transaction
Completed 500 Internal Server Error in 102ms (ActiveRecord: 5.5ms)

NoMethodError (undefined method `comment_url' for #<V1::CommentsController:0x007f85ec9a98d0>):
  app/controllers/v1/comments_controller.rb:9:in `create'

我在respond_with中与blog_post具有相同的V1::BlogPostController,我得到的回复没有错误。

作为解决方法,我使用了render json: comment

1 个答案:

答案 0 :(得分:1)

  

NoMethodError(V1 :: CommentsController的未定义方法`comment_url':0x007f85ec9a98d0

您的comments嵌套在blog_posts内,因此respond_with(comment)不起作用。相反,你需要使用

respond_with(@blog_post, comment)

<强>

respond_with comment, location: blog_post_comment_path(@blog_post, comment)