[英]respond_with didn't recognize passed object?
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
为什么response_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
NoMethodError(V1 :: CommentsController:0x007f85ec9a98d0的未定义方法`comment_url'
您的comments
嵌套在blog_posts
,因此blog_posts
respond_with(comment)
不起作用。 相反,您需要使用
respond_with(@blog_post, comment)
要么
respond_with comment, location: blog_post_comment_path(@blog_post, comment)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.