【问题标题】:how to redirect_to another page in my app?如何重定向到我的应用程序中的另一个页面?
【发布时间】:2014-03-19 16:38:24
【问题描述】:

当我的用户注册时,它最初会被重定向到其空白的个人资料页面。

但是,我需要将用户重定向到其他信息页面才能检索更多信息

我的用户控制器看起来像这样

 class UsersController < ApplicationController

 def show
   @user = User.find(params[:id])
 end

 def new
   @user = User.new
  end


  def additional_info
    @user = User.new
  end


def create
 @user = User.new(user_params)
 if @user.save
  UserMailer.welcome_email(@user).deliver
  sign_in @user
  redirect_to users: 'additional_info'
  flash[:success] = "Welcome to InYourShoes!"
  return @user       
 else
   render'new'
 end

结束

private

def user_params 
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end

结束

如您所见,additional_info 是我尝试重定向到的另一个页面。我知道我创建了 2 个用户对象,但我不确定它是否正确。坦白说,我有点迷路了。

我的页面路线是这样的:

resources :users
resources :sessions, only: [:new, :create, :destroy]
match '/additionalinfo',to: 'users#additional_info', via: 'get'

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails model-view-controller controller routes


    【解决方案1】:

    或者,您可以将重定向行更改为:

    redirect_to action: 'additional_info'
    

    假设您在路由中定义了操作:

    get :additional_info, to: 'users#additional_info' # use get rather than match
    

    【讨论】:

    • 你能解释一下get vs match的好处吗?
    • Rails 4 弃用它。 Here 一篇很好的文章,揭示了使用 match 的一些问题:安全性、不良做法、没有 RESTful ...
    • 尝试重新启动服务器或检查是否有任何 before_filter 导致no route match。我在 Rails 3.2 应用程序中尝试过,它运行良好。你能粘贴完整的错误信息吗?
    【解决方案2】:

    在你的路线中

    match '/additionalinfo',to: 'users#additional_info', via: 'get', as: :additional_info
    

    在控制器中

    redirect_to additional_info_path
    

    【讨论】:

    • 最好使用get,因为Rails 4 弃用了match。我会编辑答案。
    • 你能把这部分解释为: :additional_info 吗?是因为我在 userController 中定义它的方式吗?
    • 'as' 用于为任何路线命名。你可以给出: :info 那么你的路径将变成 info_path。
    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多