weixin_33671935 2015-05-22 08:17 采纳率: 0%
浏览 18

如何在Rails 4上使用Ajax?

I am trying to create a comment area in rails 4 using ajax. My target is to create comment and its output in same page without page loading. I have added some code. When i click on "add comment" button the data entered to DB, but does not reflect in same page.Please share with me if any one have any idea, thank u.

My codes are below:

In comment controller:

def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create
    @comment.body = params[:comment]["body"]

    respond_to do |format|
        format.html { redirect_to @article }

In show.html.erb under views/articles

<div class="col-xs-12 col-sm-12">
  <h2 class="text-center"><%= @article.title.html_safe %></h2>
    <p><%= @article.body.html_safe %></p>
        <div id="comments">
             <!--  <p><%= render :partial => @article.comments %></p> -->
             <%= render :partial => 'comments/comment', :collection => @article.comments %>
        <%= form_for([@article, Comment.new], :remote => true) do |f| %>
                <%= f.label :body, "New comment" %><br/>
                <%= f.text_area :body, type:"text", tabindex: "6", class: "form-control",  placeholder: 'your comment', rows: "4", required: true  %>
              <p><%= f.submit "Add comment" %></p>
        <% end %>

_comment.html.erb under view/comments

<%= div_for comment do %>
           Posted <%= time_ago_in_words(comment.created_at) %> ago
        <%= comment.body %>
           <%= link_to 'Delete', article_comment_path(comment.article_id, comment.id), method: :Delete, :class => 'btn btn-sm btn-warning', tabindex: "3" %>
           <%= link_to 'Edit', article_path(comment.article_id, comment.id), :class => 'btn btn-sm btn-warning', tabindex: "3" %>                         
<% end %>    

create.js.erb under views/comments

page.insert_html :bottom, :comments, :partial => 'comment', :object => @comment


config.action_view.JavaScript_expansions[:defaults] = %w(jquery rails application)
  • 写回答

2条回答 默认 最新

  • weixin_33699914 2015-05-22 09:49

    the proper way to handle this case in rails is using a remote form, this way you can interactively insert and remove objects from db. Here are two explained blog posts about remote forms in rails detailed guide about remote forms and how to partials ajax rails. This way you can submit the form without refresh an then have an handler to generate the created element after the callback from the controller. Hope this fits your question.




  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝