我有我的rails應用程序中的功能,用戶可以通過按按鈕添加收藏夾。一旦添加了收藏夾,頁面就會重新加載到屏幕的頂部。用戶喜歡的指南可能會在屏幕的中間位置出現,這讓他們不得不再次開始在頂部觀看。有沒有辦法讓它變成「最喜歡的」,但留在用戶在頁面上的位置?添加最喜歡的恢復到屏幕頂部
在index.html.erb(視圖)
<% 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