如何逃避这个重定向循环?

时间:2014-10-11 04:56:55

标签: ruby-on-rails

我正在尝试让所有用户非法尝试将其他用户的显示页面重定向到他们自己的 show 页面。

我在此代码的 else 部分中的所有尝试都没有完成这项任务。

class UsersController < ApplicationController
  def show
    if params[:id] == current_user.id.to_s
      liked_bookmark_ids = current_user.likes.pluck(:bookmark_id)
      liked_bookmarks = Bookmark.where(id:liked_bookmark_ids)
      liked_topic_ids = liked_bookmarks.pluck(:topic_id)
      @liked_topics = Topic.where(id:liked_topic_ids).order('topics.name')
    else
      # redirect_to :controller => 'users', :id => current_user.id # gives a screwy url
      # redirect_to user_path, :id => 6                            # causes a redirect loop
      # redirect_to :back                                          # causes a redirect loop  
    end
  end
end

什么是正确的方法呢?

2 个答案:

答案 0 :(得分:1)

redirect_to user_path(current_user)

答案 1 :(得分:1)

我认为更好的方法是使用filter来检查它是否是当前用户的请求。你可以这样做:

class UsersController < ApplicationController
  before_action :check_current_user, only: :show      

  def show
    liked_bookmark_ids = current_user.likes.pluck(:bookmark_id)
    liked_bookmarks = Bookmark.where(id:liked_bookmark_ids)
    liked_topic_ids = liked_bookmarks.pluck(:topic_id)
    @liked_topics = Topic.where(id:liked_topic_ids).order('topics.name')
  end

  private

  def check_current_user
    redirect_to current_user, notice: "Not authorized"  if params[:id] != current_user.id.to_s
  end
end