开发者

jQuery AJAX with Rails 3 using partials

开发者 https://www.devze.com 2023-04-12 19:45 出处:网络
I have a index view in a Rails 3 project where several line items are listed along with a corresponding count. For example:

I have a index view in a Rails 3 project where several line items are listed along with a corresponding count. For example:

Name     Count
--------------
Item A     10
Item B    278
Item c     64

The list is dynamic in length, however I know each item's id, and I have a partial which disp开发者_运维知识库lays a passed-in count.

How would I change this setup to display the count via AJAX (jQuery)?

For example, I would want the intial spot where the count is to be a spinner. And the spinner would be replaced with the actual count after being triggered somehow. But I need this for each and every item in the list.

For your answer to be useful for me please provide detailed steps and sample code. Thank you!


I eventually came up with a solution for this.

In the controller (samples_controller.rb):

# GET /samples/1/count
def count
  sample = Sample.find(params[:id])
  count = sample.data.count
  count_title = "#{number_with_delimiter(count)} samples"

  respond_to do |format|
    format.js {
      if count > 0
        render :partial => 'partials/count', :locals => {:count => count, :count_title => count_title}
      else
        render :nothing => true
      end
    }
  end
end

In the view (samples/index.html.erb):

<table>
<% @samples.each do |sample| %>
<tr>
  <td class="sample_count">
    <div data-id='<%= sample.id %>'>
      <img src="/images/icons/spinner.gif"/>
    </div>
  </td>
<tr>
<% end %>
</table>

The javascript in the view:

<script type='text/javascript'>
    $(document).ready(function() {
        $('.sample_count div').each(function() {
            $(this).load('/samples/' + $(this).attr('data-id') + '/count');
        });
    });
</script>

In the config/routes.rb:

controller :samples do
  get "samples" => :index
  delete "samples/:id" => :destroy
  get "samples/:id/count" => :count
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号