【问题标题】:Redirecting Users in rails在 Rails 中重定向用户
【发布时间】:2015-02-04 20:18:32
【问题描述】:

我有一个个人资料控制器,允许用户访问他们自己的个人资料,但不能访问其他用户的个人资料。

当我访问如下网址时:http://localhost:3000/en/profiles/2。如果 URL 对应于 disown 个人资料,我希望我的用户被重定向到他们自己的个人资料。我该如何处理?

我的个人资料控制器中的实际显示操作如下所示:

  def show
    @profile = Profile.find(params[:id])
    @user = current_user 
    @profile  = @user.profile
  end

这个方法我已经试过了,但是不行

  def correct_user
    redirect_to(profile_path) unless current_user == (@profile.user if @profile) 
  end

【问题讨论】:

  • 请详细提供您的问题,以便其他人能够准确了解您在寻找什么。请提及,您要实现什么目标,您面临的问题是什么,到目前为止您做了什么,如果可能,请提供示例代码。不要忘记标记相关技术,以便您的问题能够传达给合适的人。

标签: ruby-on-rails ruby redirect url-redirection


【解决方案1】:

您可能应该将逻辑移至before_action

before_action :find_profile, :enforce_current_profile

def show
end

protected

def find_profile
  @profile = Profile.find(params[:id])
end

def enforce_current_profile
  unless @profile && @profile.user == current_user
    redirect_to(profile_path)
  end
end

但是,您真正想做的是将配置文件控制器转换为resource,而不是路由文件中的resources

resource :profile

这样,Rails 就会生成

GET /profile

而不是

GET /profile/2

您将不需要任何控制。设置好了

def show
  @user = current_user
  @profile = @user.profile
end

使用resource 而不是resources 不会提供index 操作,但我怀疑您是否需要它。

【讨论】:

  • 这会引发此错误找不到没有 ID 的配置文件 def find_profile @profile = Profile.find(params[:id]) end
  • 如果你使用resource,你没有任何id。您需要相应地调整您的代码。我假设如果您有该用户,您已经知道他的个人资料 ID。
  • 我只是在我的配置文件控制器中使用您向我建议的内容,但我收到此错误找不到没有 ID 的配置文件 def find_profile @profile = Profile.find(params[ :id]) 结束我的控制器路线是资源 :profile
  • 也许我只是不需要使用 before_action :find_profile
  • 抱歉,你能告诉我为什么我在编辑我的个人资料后重定向到localhost:3000/1/profile 吗?我的更新操作是@profile = current_user.profile respond_to do |format| if @profile.update(profile_params) flash[:notice] = "emplois à été mis à jour!" format.html { redirect_to profile_path } else format.html { render action: 'edit' } end end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2012-11-27
  • 2015-03-21
  • 2011-02-24
  • 1970-01-01
  • 2010-11-02
相关资源
最近更新 更多