2016-04-17 6 views
0

Rails 4.2.6response_with не распознал переданный объект?

маршруты:

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", "[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' 

У меня есть один и тот же respond_with с blog_post в V1::BlogPostController, и я получил ответ без ошибок.

В качестве обходного пути я использовал render json: comment

ответ

1

NoMethodError (не определен метод `comment_url» для V1 :: CommentsController: 0x007f85ec9a98d0

Ваш comments вкладываются blog_posts, так respond_with(comment) не работает Вместо этого вам необходимо использовать

respond_with(@blog_post, comment)

или

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

только второй подход работал для меня –

Смежные вопросы