我的 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 %>
指南控制器.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