如何使用AJAX在Rails中执行POST操作

时间:2016-04-11 22:22:20

标签: ruby-on-rails ajax

  

方案

我创建了一个用于学习Rails和Bootstrap的简单应用程序。这个应用程序的功能是允许用户为名人提供昵称,也喜欢昵称。您可以在http://celebnicknames.herokuapp.com

查看

我有一个link_to按钮,用于在我的 home / index.html.erb 中为名人发布喜欢的内容:

<%= link_to home_updatelike_path(id: nickname.id, search: @search ), method: :post, remote: true, class: "update_like btn btn-xs btn3d pull-right" do %>
    <i class="glyphicon glyphicon-thumbs-up"></i>
<% end %>

我的home_controller.rb中对于post方法的相应代码是:

def updatelike
       @like = Like.new(:nickname_id => params[:id], :ip_address => request.remote_ip)
       @like.save

     respond_to do |format|
      format.html { redirect_to root_path("utf8"=>"✓", "search"=>params[:search], "commit"=>"Search") }
      format.json { head :no_content }
      format.js   { render :layout => false }
    end
end

updatelike.js.erb 中的代码如下:

$('.update_like').bind('ajax:success', function() {

});

现在,我想要实现的是在不执行页面重新加载的情况下提交类似内容。

  

问题:

每当我按下按钮时,数据库操作就完成了,但除非我重新加载,否则更改不会反映在页面中。请引导我完成这个noob问题,并提供资源的链接,这些资源解释了使用带有Rails的AJAX。

  

修改

以下是整个主页/ index.html.erb

<div class="jumbotron col-md-6 col-md-offset-3">
    <h1 class='text-center'>Nicknamer</h1>
</div>

<div class="container">

        <div class="row">
            <div class="col-sm-8 col-sm-offset-2 bottom50">
                <%= form_tag(root_path, :method => "get", id: "search-form", type: "search") do %>
                <div class = "form-group" >
                    <div class = "col-sm-9  " >
                        <%= text_field_tag :search, params[:search], placeholder: "Name", class: "form-control" %>
                    </div>
                    <div class = "col-sm-3" >
                        <%= submit_tag "Search", class: "btn btn-default btn-block btn-success"%>
                    </div>
                </div>
                <% end %>
            </div>
        </div>

        <% @names.each do |name| %>
        <div class="col-md-6 col-xs-8 col-md-offset-3 col-xs-offset-2 bottom50">

            <!-- ===== vCard Navigation ===== -->
            <div class="row w">
                <div class="col-md-4">
                    <% if name.sex == true %>
                        <%= image_tag("mal.jpg", :alt => "", class: "img-responsive") %>    
                    <% else %>
                        <%= image_tag("fem.jpg", :alt => "", class: "img-responsive") %>    
                    <% end %>
                </div><!-- col-md-4 -->

            <!-- ===== vCard Content ===== -->
                <div class="col-md-8">
                    <div class="row w1">
                        <div class="col-xs-10 col-xs-offset-1">
                        <h3><%= "#{name.name}" %></h3>
                        <hr>
                        <h5>Also known as</h5>

                            <% name.nicknames.each do |nickname| %>
                                <div class = "row w2 bottom10">
                                    <% if nickname.name_id == name.id %>
                                        <div class="col-xs-7">
                                            <%= nickname.nickname %>
                                        </div>
                                        <div class="col-xs-3 text-right">
                                            <%= pluralize(nickname.likes.count, 'like') %>
                                        </div>
                                        <div class="col-xs-1">
                                            <%= link_to home_updatelike_path(id: nickname.id, search: @search ), method: :post, remote: true, class: "update_like btn btn-xs btn3d pull-right" do %>
                                            <i class="glyphicon glyphicon-thumbs-up"></i>
                                            <% end %>
                                        </div>                                      
                                    <% end %><!-- if -->
                                </div><!-- row w2 -->   
                            <% end %><!-- do -->

                            <div class = "row w3 bottom30">
                            <%= form_for @addnickname, as: :addnickname, url: {action: "addnickname"} do |f| %>
                                <div  class = "form-group" >
                                    <%= f.hidden_field :name_id, :value => name.id %>
                                    <%= f.hidden_field :search, :value => @search %>
                                <div class = "col-xs-9">
                                    <%= f.text_field :nickname , :required => true, class: "form-control" %>
                                </div>
                                <div class = "col-xs-3">
                                    <%= f.submit "Add", class: "btn btn-default btn-info"%>
                                </div>
                                </div>
                            <% end %>
                            </div>

                        </div><!-- col-xs-10 -->
                    </div><!-- row w1 -->
                </div><!-- col-md-8 -->
            </div><!-- row w -->
        </div><!-- col-lg-6 -->
        <% end %>
    </div><!-- /.container -->

这是整个 home_controller.rb

class HomeController < ApplicationController
  def index
    @addnickname = Nickname.new
    if params[:search]
        @search = params[:search]
        @names = Name.search(params[:search])
    else
        @names = Name.all
    end
  end

  def addnickname
    @addnickname = Nickname.new(:nickname => params[:addnickname][:nickname], :name_id => params[:addnickname][:name_id])

    if @addnickname.save
      redirect_to root_path("utf8"=>"✓", "search"=>params[:addnickname][:search], "commit"=>"Search")
    else
      render :new
    end
  end

  def updatelike
       @like = Like.new(:nickname_id => params[:id], :ip_address => request.remote_ip)
       @like.save

     respond_to do |format|
      format.html { redirect_to root_path("utf8"=>"✓", "search"=>params[:search], "commit"=>"Search") }
      format.json { head :no_content }
      format.js   { render :layout => false }
    end
    end

private
  def addnickname_params
    params.require(:addnickname).permit(:name_id, :nickname, :search)
  end
end

1 个答案:

答案 0 :(得分:0)

好的,所以你需要一种方法来识别需要改变的数字的div:

<div class="col-xs-3 text-right">
  <%= pluralize(nickname.likes.count, 'like') %>
</div>

最简单的方法是在id上使用div属性,该属性对应于昵称的(唯一)数据库ID。 Rails的div_for<%= div_for(nickname, class: "col-xs-3 text-right") do %> <%= pluralize(nickname.likes.count, 'like') %> <% end %> 。所以你可以将上面的代码更改为:

div

这将生成id nickname_1,如$("nickname_#{@like.nickname.id}").html(@like.nickname.likes.count); (如果昵称的此ID为1)。

现在,在您的javascript模板中,您可以轻松定位需要更新的div:

ajax:success

此处不需要aml:length aml:hasDataType "xs:double" ; aml:hasValue "35"^^xsd:double ; rdf:type aml:Attribute ; schema:name "length" . 绑定,因为您正在渲染javascript模板。在模板中,您可以访问控制器中设置的实例变量 - 就像您可以从HTML模板中一样。上面的代码旨在用新计数替换包含like count的div的内容。