在Rails中管理条件redirect_to
我的系统中有多种用户类型,通常根据用户是否登录以及 current_user.user_type 向每个用户显示存储信息的不同视图和模板。结果,我有很多这样的事情:
#controller
@project = Project.find(params[:id])
if current_user.user_type == "Company"
redirect_to :controller => "companies", :action => "home"
elsif current_user.user_type == "Contractor"
@contractor = Contractor.find(current_user.user_type_id)
redirect_to :controller => "contractors", :action => "home"
elsif current_user.user_type == "Customer"
redirect_to :controller => "companies", :action => "list"
end
这是我的第一个 Rails 项目,我很确定这是糟糕的设计。有哪些简单干净的方法可以更好地做到这一点?
I have multiple user types in a system that shows each user different views and templates of the stored information, often based on whether they are logged in and what current_user.user_type is. As a result, I have lots of this:
#controller
@project = Project.find(params[:id])
if current_user.user_type == "Company"
redirect_to :controller => "companies", :action => "home"
elsif current_user.user_type == "Contractor"
@contractor = Contractor.find(current_user.user_type_id)
redirect_to :controller => "contractors", :action => "home"
elsif current_user.user_type == "Customer"
redirect_to :controller => "companies", :action => "list"
end
This is my first Rails project and I am pretty sure this is poor design. What are simple clean ways of doing this in a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有很多这样的代码,那么您的控制器确实有多种用途。假设您的控制器类似于 InfoController,它是某些 Info 模型的 REST 视图,请问自己:
您的操作的核心部分是什么,数据或访问的用户
它?
您是否根据谁来做出决定
要求采取行动? (就像储蓄一样,
删除等)
这些决定可以在
信息模型,而不是在控制器中?
对我来说,似乎您应该为每个模型创建不同的控制器,并且每个操作只进行一个重定向。在您的视图中,您可以使用 polymorphic_paths 之类的东西链接到您的控制器。
如果您决定不这样做,我只需将该代码放入
case
语句中,而不是放在if
中。If you're having a lot of code like this, is a code smell that your controller is really serving multiple purposes. Assuming your controller is something like InfoController, which is a REST view for some Info model, ask yourself:
What is the central piece of your actions, the data or the user who access
it?
Are you taking decisions based on who
requests the actions? (Like saving,
deleting, etc)
Can these decisions be taken in the
Info model, rather than in the controller?
To me, seems like you should create different controllers for each model, and make just one redirect per action. In your views, you can use things like polymorphic_paths to link up to your controllers.
If you decide not to do this, I'd just put that code in a
case
statement instead of anif
.还可以使用约束,如下所示: Rails 3 中以用户为中心的路由
或如下所示的范围路由: 使用 lambda 来实现 Rails 3 路由约束
Can also use constraints as seen here: User-centric Routing in Rails 3
Or scoped routes as seen here: Use lambdas for Rails 3 Route Constraints
当用户在您的应用程序中登录时,您必须有一些代码将他们重定向到某个地方。
这是您要放置代码的位置。
你可能想使用:
When a user hit login in your application, you must have some code to redirect them somewhere.
This is where you want to put your code.
and you probably want to use: