pawel7318
pawel7318

Reputation: 3593

Rails - select multiple page elements and perform action on them

I'm working on simple photo gallery app in Rails. I have a view where thumbnails are displayed and I have separate buttons for every (to delete or move that photo to different album.

What I would like to have is a possibility to select a bunch of them and use action for all selected.

Tick-boxes would be good enough but best would be if I can select them with ctrl-click, shift-click or creating squere with mouse. One other way would be press action button first, then click thumbnails and confirm.

I know more or less how to make such of things from scratch (using HTML, JS, jquery and PHP) but there's no point to invent the wheel one more time, spend a lot of time doing it and make it worst that the one is already available..

Is there a gem to achieve this ? Or at least some useful helper functions (like form_for for example) ?

Upvotes: 1

Views: 425

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

We've done this before. Here's what we did (we use inherited_resources):

#config/routes.rb
resources :controller do
   delete 'destroy(/:id)', action: 'destroy', as: 'multi_destroy'
end

#app/controllers/your_controller.rb
def destroy
    id = params[:id] 

    #Multi
    if id.kind_of?(Array)
        ids = Model.where(:id => id.split(','))
        ids.destroy_all if ids.exists?

        respond_to do |format|
            format.json { render json: "success".to_json }
            format.html { redirect_to collection_path }
        end

    else
        destroy! { collection_path }
    end

end


#app/views/images/index.html.erb
<div class="images">
    <% collection.each do |image| %>

            <!-- Image -->
            <div class="image" id="<%= image.id %>">
                <%= check_box_tag "id[]", image.id, false, class: "multi-delete" %>
            </div>

    <% end %>

    <%= button_to "Remove Selected", multi_destroy_images_path, method: :delete, id: "multi-delete", data: { confirm: "Are You Sure?" } %>
</div>

Upvotes: 1

Related Questions