I have comments controller that creates comments on show.html.erb of a book controller.
Users can also post comments on another view, which is different from show.html.erb above but still uses the same comment form. This is index.html.erb for postcomments controller that inherits from comments controller. I created this just for this purpose.
My purpose is to, when comment is saved, redirect to show.html.erb (book) when comment was created there and redirect to index.html.erb (postcomments)when comment was created there -- that is to say, remain on the same page.
Right now redirect to show.html.erb (book) works fine. But when I create comment on index.html.erb (postcomments), it redirects to show.html.erb (book).
comments controller (only relevant section):
if @comment.save
redirect_to comment_create_redirect_path, notice: "Success!~"
else
redirect_to book_path(@post.book.id), alert: "Failure!"
end
end
private
def comment_params
params.require(:comment).permit(:text)
end
private
def comment_create_redirect_path
book_path(@post.book.id)
end
postcomments controller (full; I've tried adding the entire create action with redirect switched; didn't work):
class PostcommentsController < CommentsController
def index
@posts = Post.all
end
private
def comment_create_redirect_path
postcomments_path
end
index.html.erb (postcomments, relevant section):
<%= form_for(post.comments.build, url: "/posts/#{post.id}/comments") do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit "Post comment"%>
</p>
<% end %>
<% post.comments.each do |comment| %>
<p>
<%= comment.user.try(:email) %>
<%= comment.text %>
</p>
<% end %>
routes:
resources :users do
resources :books, shallow: true
end
resources :books do
resources :posts, shallow: true
end
resources :posts do
resources :comments, shallow: true
end
resources :postcomments, shallow: true
Please let me know if you'd like anything else.
You can use redirect_back
helper. You need to provide a fallback location.
redirect_back fallback_location: @post.book
https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_back
You can get referer path and redirect action to this path:
# comments_controller.rb
def comment_create_redirect_path
return root_path if request.try(:referer).blank?
URI(request.referer).path
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.