0

我的网站上有一个页面,用户可以通过接受或拒绝邀请来响应邀请。

他们的响应以布尔值“接受”的形式存储在数据库中,并用于将“选定”或“未选定”类(选定使文本变为橙色)应用于“参加”div 或“未参加”div。

<% @going, @not_going = invite.accepted ? ['selected','not_selected'] : ['not_selected','selected'] %>

    <%= link_to(outing_invite_accept_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %>
            <div class="attending_div <%= @going %>">
                attending
            </div>
    <%end %>
    <%= link_to(outing_invite_decline_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %> 
            <div class="attending_div <%= @not_going %>">
                not attending</div>
            </div>
    <% end %>

当任一 div 被点击时,它被转移到适当的控制器动作:

def invite_accept
    @outing = Outing.find(params[:outing_id])
    @invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
    @invite.update_attribute(:accepted, true)
    redirect_to({:action => "index"})
end  

def invite_decline
    @outing = Outing.find(params[:outing_id])
    @invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
    @invite.update_attribute(:accepted, false)
    redirect_to({:action => "index"})
end

和现在一样,这段代码工作得很好。但它需要刷新索引页面才能生效。

我知道可以使用附加到适当 div 上的侦听器的 jQuery ajax 调用来更新页面而无需刷新,但我不知道这样的调用会是什么样子,或者从哪里开始,真的......

4

1 回答 1

4

您想使用铁路的 link_to :remote => true

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

为了处理回调,您可以绑定到将触发的某些事件。例如:

<%= link_to "Click Me!", some_path, :class => 'ajax', :remote => true %>

<script>
  jQuery(function($) {
    $("a.ajax")
      .bind("ajax:loading", console.log('loading'))
      .bind("ajax:complete", console.log('complete'))
      .bind("ajax:success", function(event, data, status, xhr) {
        console.log(data);
      })
      .bind("ajax:failure", function(xhr, status, error) {
        console.log(error);
      });
  });
</script>

这个页面也写得很好:http ://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

于 2012-06-28T00:23:42.163 回答