如何使用路由别名改进重定向



我正在为应用程序使用 devise 并且我不喜欢我的应用程序在成功登录后重定向的方式。这是rake routes的输出:

   manager_root GET    /managers/dashboard(.:format)      managers#dashboard
   student_root GET    /students/dashboard(.:format)      students#dashboard
enterprise_root GET    /enterprises/dashboard(.:format)   enterprises#dashboard

到目前为止我有什么

def after_sign_in_path_for(resource)               
  "/#{current_user.profile_type.pluralize}/dashboard"
end

我试过什么

def after_sign_in_path_for(resource)               
  "#{current_user.profile_type}"_root_path
end
#=> application_controller.rb:17: syntax error, unexpected tIDENTIFIER, expecting keyword_end
def after_sign_in_path_for(resource)               
  "#{current_user.profile_type}_root_path"
end
#=> ERROR URI::InvalidURIError: the scheme http does not accept registry part:localhost:3000enterprise_root_path (or bad hostname?)

注意

  • 我只有一个名为User的设计模型,它有一个名为profile_type的列,其值可以是'enterprise''student''manager'

  • 我只想使用我的路由别名。

  • 到目前为止,我得到了什么,所以我只想改进它。

我认为这应该适合您:

def after_sign_in_path_for(resource)               
  polymorphic_url([current_user.profile_type, :root])
end

通过纳什的回答,我搜索了多态的更好用法,并做出了自己的答案。

这是获取帖子评论和新闻评论的URL的常用方法

# parent may be a post or a news
if Post === parent
  post_comments_path(parent)
elsif News === parent
  news_comments_path(parent)
end

Rails 提供了一种生成多态 url 的简单方法。因此,我们可以使用该polymorphic_path来获取postnews注释的网址

# "/posts/1/comments" or "'news/1/comments"
polymorphic_path([parent, Comment])

这可以获取帖子和新闻的网址

# "http://example.com/posts/1/comments" or "http://example.com/news/1/comments"
polymorphic_path(parent)

polymorphic_path使多态 URL 生成变得更加容易和简单。还有一个名为 polymorphic_url 的方法,它与polymorphic_path相同,只是polymorphic_url生成包含主机名的完整 URL。

除此之外,rails 还为polymorphic_path/polymorphic_url提供了新的和编辑的操作

new_polymorphic_path(Post)    # "/posts/new"
new_polymorphic_url(Post)     # "http://example.com/posts/new"
edit_polymorphic_path(post)   # "/posts/1/edit"
edit_polymorphic_url(post)    # "http://example.com/posts/1/edit"

就我而言,我只是

def after_sign_in_path_for(resource)
  polymorphic_path [current_user.profile_type, :root]
end

试试这个

def after_sign_in_path_for(resource)               
  send("#{current_user.profile_type}_root_path")
end

最新更新