ROR 3 conditions in routes.rb

2019-07-29 05:35发布

问题:

Is there a way to specify conditional statement inside routes.rb - I would like the root_path to depend on whether the user is signed in or not. perhaps there are other ways of accomplishing this?

Thanks!

回答1:

Actually I think you can using advanced constraints it is documented here...

You would define a def matches?(request) to check if the user is signed in, and use two routes one when with a constraint of signed in and one when not. Although I am not sure if the session is available when that custom constraint is executed.

Although I agree with SpyrosP it would be better to do it in the Controller.



回答2:

No, you cannot do that. The routes do not rely on conditions that are based on model code. Anybody can call a route, so you cannot depend on that anyway.

Instead, just add a "before_filter :authenticate"(using sessions) on the controllers that you want to protect. If somebody tries to access your admin controller without being an admin, they will be redirected to login or anywhere you like.



回答3:

I think the previous answers (suggesting a before_filter in the controller is more appropriate) are missing the OP's use case slightly. There are still advantages to doing it as a conditional route/advanced constraint. It doesn't replace having a before filter in the controller to prevent unauthorized direct access. But, for instance, having a redirect_to root_path route directly to e.g. a user's profile when he is signed in, or the front page when not, preserves flash messages that would otherwise be lost in a second redirect in the before filter. More elegant IMHO to use the advanced constraint approach (assuming of course that the session is in fact available when the custom contraint is tested). Not to mention, in this type of instance, why not save the extra redirect (since it involves a whole other HTTP(S) transaction)?

UPDATE: If you're using Devise, this article describes an even better approach. Just implemented it myself and it works great, and it's clean.

Also, comments to explain down votes are always appreciated, not just for the author but for others who read the answer so they know why it might not be a reasonable response.