Mini John
Mini John

Reputation: 7941

How to redirect_to "nothing"

I'm working with acts_as_votable.

So my routes look like this:

  resources :git do
    member do
      get :like
      get :unlike
    end
  end

I didn't create the files like.html.erb & unlike.html.erb cause i don't need the View.

my Like Action:

  def like
    @git = Git.find(params[:id])
    @git.liked_by current_user
    redirect_to :back
  end

My Problem is, the Git Index file has a looooong list and if anyone "Likes" it the page is refreshed from the redirection and the user has lost his scroll position.

How can i block out the redirection ? To just do nothing ?

My View:

<span><i class="fa fa-thumbs-up"></i> <%= link_to "Like", like_git_path(git) %></span>
<div class="b2-widget-count" style="display: inline-block">
  <i></i><u></u><div class="b2-widget-val"><%= git.likes.size %></div>
</div>

Upvotes: 4

Views: 1474

Answers (2)

methyl
methyl

Reputation: 3312

The best way is to send head :no_content or render nothing: true. I recommend first one due to problems with jquery on the second.

  def like
    @git = Git.find(params[:id])
    @git.liked_by current_user
    render text: @git.likes.size
  end

Change your routes to POST.

Then, make sure you have gem jquery-rails line in the Gemfile.

Add this two lines to top of your application.js file.

//= require jquery
//= require jquery_ujs

Add this lines to bottom of application.js file:

$(document).ready(function(){
  $('.like-button, .unlike-button').click(function(e){
    e.preventDefault();
    url = $(e.currentTarget).attr('href');
    $.post(url).done(function(data){
      $(e.currentTarget).closest('.b2-widget-val').html(data);
    });
  });
});

Add corresponding classes (like-button, unlike-button) to your link_to helpers.

Upvotes: 3

Matt Adelman
Matt Adelman

Reputation: 79

How does the user get into these functions? Do they click a button? If so, check out button_to. Also, this may be better suited as a POST action.

Upvotes: 0

Related Questions