Reputation: 398
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?
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", "[email protected]"]]
(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.
As a workaround I have used render json: comment
Upvotes: 0
Views: 24
Reputation: 33542
NoMethodError (undefined method `comment_url' for V1::CommentsController:0x007f85ec9a98d0
Your comments
are nested inside blog_posts
, so respond_with(comment)
doesn't work. Instead you need to use
respond_with(@blog_post, comment)
or
respond_with comment, location: blog_post_comment_path(@blog_post, comment)
Upvotes: 1