我做了一个评论部分我的帖子的意见后,用AJAX刷新页面,我有remote: true
工作表上,所以当你按下回车键,并提交“新的评论“形式,它会在后台更新(评论已创建,页面不重定向或更改),但无法将其加载到页面上。您必须刷新页面才能看到它们。轨道4:提交远程形式不同的控制器
保存后,我可以在评论控制器中执行redirect_to :back
,但这会将用户置于页面顶部,而不是留下来查看评论。
我已将render 'posts#show'
储存在评论控制器创建操作后尝试将您发送至/comments/posts/:slug/
。如果它实际上呈现了帖子展示动作,我认为这会起作用。
评论控制器:上展后视图
class CommentsController < ApplicationController
before_action :find_commentable
def show
end
def new
@comment = Comment.new
end
def create
@comment = @commentable.comments.new comment_params
@comment.author = current_user if current_user
@comment.save
end
private
def comment_params
params.require(:comment).permit(:body, :author_id, :post_id)
end
def find_commentable
@commentable = Comment.find(params[:comment_id]) if params[:comment_id]
@commentable = Post.find_by_slug(params[:post_id]) if params[:post_id]
end
end
评论部分:
%ul#post-comments
= render 'comment_feed'
= form_for [@post, Comment.new], remote: true do |f|
= f.text_field :body, class: 'js-new-comment-field', placeholder: "Write a comment..."
帖/ show.js.erb:
$("#post-comments").html("<%= escape_javascript render("comment_feed") %>");
routes.rb中:
resources :posts do
collection do
match 'search' => 'posts#search', via: [:get, :post], as: :search # For ransack search
end
resources :comments
end
resources :comments do
resources :comments # Replies on comments
end
做你有解决方案吗? – uzaif
还没有,但有点接近。我没有做任何服务器端,所以也许我只需要弄清楚如何用它创建的评论来回应ajax请求。此页面对目前为止有帮助http://guides.rubyonrails.org/working_with_javascript_in_rails.html –
请在您的网络标签中查看它会帮助您 – uzaif