【问题标题】:Ruby on Rails implement Ajax Post and CommentsRuby on Rails 实现 Ajax 发布和评论
【发布时间】:2016-05-14 01:33:50
【问题描述】:

有人可以帮助我吗?我正在尝试在我的项目中实现 AJAX,我需要做的事情应该很容易,但对我来说,这已经是疯狂的一天。 我的想法是当用户添加新评论时应该出现 没有重新加载页面,下面跟随我的控制器、视图和路线。啊删除我做了一些有效的事情。

这里是 /app/controller/cmets_controller.rb

发布 app/controller/posts_controller.rb

查看评论 /app/views/cmets/_template.html.slim

查看评论 /app/views/cmets/_form.html.slim

Views Pots /app/views/posts/show.html.slim

使用删除评论的解决方案

【问题讨论】:

  • 如何使用 $.ajax,将评论文本发送到您的控制器,验证它,如果有效则响应 true。收到 true 后,$(comment-holder).append(the new comment).. 哦,您正在寻找 $.ajax 语法?。
  • 我正在尝试类似 jQuery -> # 创建评论 $(".comment-form") .on "ajax:beforeSend", (evt, xhr, settings) -> $( this).find('textarea') .addClass('uneditable-input') .attr('disabled', 'disabled'); .on "ajax:success", (evt, data, status, xhr) -> $(this).find('textarea') .removeClass('uneditable-input') .removeAttr('disabled', 'disabled') .val(''); $(xhr.responseText).append($("#cmets_container")).show('slow')
  • 请将您的代码发布为文本而不是快照?
  • 对不起,这是我的第一篇文章,从现在开始我将只发布文本代码。

标签: javascript ruby-on-rails ruby ajax


【解决方案1】:
create.js.erb

$("#comments").html("<%= escape_javascript(render partial: "comments/template", collection: @post.comments, as: :comment) %>");

_template.html.erb
<p class="comment-name"><%= link_to comment.user.name, user_path(comment.user_id)%>
  <span class="comment-content"><%= comment.content %></span> 
</p>
<p class="comment-time"><%= time_ago_in_words(comment.created_at) %></p>

CommentsController

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)
    @comment.save
    respond_to do |format|
      format.html { redirect_to :back }
      format.js 
    end 
end   

这可能太简单了,但也许它会激发一些东西。

【讨论】:

  • 为了更清楚一点,我正在使用 gem 'acts_as_commentable_with_threading',评论控制器可以在任何其他模型中使用,您给我的解决方案将改变事情的工作方式。谢谢。
猜你喜欢
  • 2016-04-17
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多