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



场景

我创建了一个简单的应用程序来学习Rails和Bootstrap。这个应用程序的作用是允许用户给名人起昵称,也可以喜欢这些昵称。你可以在http://celebnicknames.herokuapp.com

我有一个链接按钮,可以在我的主页/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

js.erb中的代码如下:

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

现在,我想要实现的是在不执行页面重新加载的情况下提交一个赞。

问题:

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

编辑

这是整个home/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

好的,所以您需要一种方法来用需要更改的数字来识别div:

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

最简单的方法是在div上有一个id属性,该属性对应于昵称的(唯一)数据库id。Rails有一个名为div_for的辅助方法。所以你可以把上面的代码改成这个:

<%= div_for(nickname, class: "col-xs-3 text-right") do %>
   <%= pluralize(nickname.likes.count, 'like') %>
<% end %>

这将生成具有类似nickname_1iddiv(如果昵称的这个id是1)。

现在,在您的javascript模板中,您可以轻松地针对需要更新的div:

$("nickname_#{@like.nickname.id}").html(@like.nickname.likes.count);

ajax:success绑定在这里是不必要的,因为您正在呈现一个javascript模板。在模板中,您可以访问控制器中设置的实例变量,就像从HTML模板中访问一样。上面的代码旨在用新的计数替换包含点赞计数的div的内容。

相关内容

  • 没有找到相关文章

最新更新