Search code examples
ruby-on-railsruby-on-rails-5

rails redirect from child create to child show


I am sure there is a solution for this but I am not seeing it. I want to redirect to the show page for my child after creation.

I have just created a child record for my parent record in my child controller like so:

def create
   @article = Article.find(params[:article_id])
   @comment = article.comments.create(comment_params)
   redirect_to "/articles/#{@article.id}/comments/#{@comment.id}"
end

...
private

def comment_params
    params.require(:comment).permit(:commenter, :body)

I would like to do something like redirect_to @comment

Is there a way to do this? Once I did the above I also got an error with this prebaked code from the scaffold creation:

<%= link_to 'Edit', edit_comment_path(@comment) %>

I feel like there is something wrong with my routes maybe or I am not referencing the path for my child correctly.

routes.rb:

resources :articles do
  resources :comments
end
  1. How do I redirect to the "show" of my child correctly in the create method of my controller
  2. Why would my edit path be broken in my child show view?

thanks


Solution

  • Try below code:

    controller

    def create
       @article = Article.find(params[:article_id])
       @comment = article.comments.create(comment_params)
       redirect_to article_comment_path(@article,@comment)
    end
    

    view

    <%= link_to 'Edit', edit_article_comment_path(@article, @comment) %>
    

    routes

    resources :articles do
      resources :comments
    end