KingOfBabu
KingOfBabu

Reputation: 409

Ruby on Rails - Refresh data when button pressed

I have a website which contains photos and videos and 3 buttons. One show only photos, one only videos and the last one show photos & videos. I have two different tables in the database (photos, videos) which contains only the name of the file. Their is no relationship between them.
Here is a example of my AJAX used to only show videos :

jQuery(document).ready(function() {
    $('#btn-videos').on('click', function(e){
    e.preventDefault();
    $.ajax({
    type:'GET',
    url:'/galerie',
    dataType: 'json',
    data: { 'type' : "videos", }
    });
    });
});

Here is my galerie controller :

  def index
     case params[:type]
     when "videos"  
        @medias = Video.order('created_at DESC')
     when "images" 
        @medias = Picture.order('created_at DESC')
     else 
        @medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
     end
  end

My AJAX is calling the controller but it doesn't update the view.
Is their a (better) way to do this ?
I'm also wondering if its possible to do this line using only sql :

@medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)

Upvotes: 0

Views: 783

Answers (1)

Vineeth
Vineeth

Reputation: 173

You can do this in two ways:

  1. send a remote request through your button and handle data update on index.js.erb file (in views folder). You can refer to this link.
  2. Use ajax in js file in your asset. Once the ajax request is successful you need to replace your old data with your requested new data.

    $('#btn-videos').on 'click', ->
       e.preventDefault();
       $.ajax
         type:'GET',
         url:'/galerie',
         dataType: 'json',
         data: { 'type' : "videos", }
         success: (data) ->
           console.log(data)
    

Upvotes: 1

Related Questions