简体   繁体   English

response_with无法识别传递的对象?

[英]respond_with didn't recognize passed object?

Rails 4.2.6 Rails 4.2.6

routes: 路线:

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

Comments controller: 评论控制器:

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

Why respond_with method didn't respond with comment object? 为什么response_with方法没有对comment对象进行响应?

Logs: 日志:

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'

I have the same respond_with with blog_post in V1::BlogPostController and I got a response without errors. 我有同样的respond_withblog_postV1::BlogPostController和我有没有错误的响应。

As a workaround I have used render json: comment 作为一种解决方法,我使用了render json: comment

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

Your comments are nested inside blog_posts , so respond_with(comment) doesn't work. 您的comments嵌套在blog_posts ,因此blog_posts respond_with(comment)不起作用。 Instead you need to use 相反,您需要使用

respond_with(@blog_post, comment)

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM