0

I have a function on my rails app where a user can add a favourite by pressing a button. Once the favourite is added, the page reloads to the top of the screen. The guideline that the user has favourited could be half way down the screen and it's annoying for them to then have to start viewing at the top again. Is there a way for it just to be changed to 'favourite' but stay where the user is on the page?

In index.html.erb (views)

<% if !current_user.favourite_guidelines.select{|f| f.guideline_id==guideline.id}.any? %>
                    <%= link_to guidelines_favourite_path(guideline_id: guideline.id, type: "favourite"), method: "get", class: "btn btn-small main" do%>
                    <i class="icon icon-star"></i> Favourite
                    <% end %>
                <% end %>
                <% if current_user.favourite_guidelines.select{|f| f.guideline_id==guideline.id}.any? %>
                <%= link_to guidelines_favourite_path(guideline_id: guideline.id, type: "unfavourite"), method: "get", class: "btn btn-small main" do%>
                <i class="icon-star-empty"></i> Unfavourite
                <% end %>

guidelines_controller.rb

def favourite
   type = params[:type]
   if type == "favourite"
      @guideline= Guideline.find_by_id(params[:guideline_id])
          current_user.favourite_guidelines.build(:guideline_id => @guideline.id).save
           redirect_to :back


    elsif type == "unfavourite"
      @guideline= Guideline.find_by_id(params[:guideline_id])

     current_user.favourite_guidelines.where(:guideline_id => @guideline.id).destroy_all
     redirect_to :back

    else
    # Type missing, nothing happens
   redirect_to :back, notice: 'Nothing happened.'
    end
  end
tessad
  • 1,209
  • 3
  • 20
  • 40

2 Answers2

1

You would typically make this happen by using AJAX so that only part of your page is reloaded, keeping the user's scroll position. The Rails Guides have some incomplete information here: http://guides.rubyonrails.org/ajax_on_rails.html

There's also a RailsCast on the subject. They're very helpful and worth buying.

Dan Wich
  • 4,923
  • 1
  • 26
  • 22
1

redirect_to loads the page, that's why it's at the top.

OR

  • you can do an AJAX call and that way the page won't redirect. you would then just have the response update the page the the user is on, and so the user wouldn't be redirected anywhere
Community
  • 1
  • 1
AdamT
  • 6,405
  • 10
  • 49
  • 75