简体   繁体   中英

Rails 'routing' based on model properties

I am trying to do different things on the home page of my application based on properties of the currently authenticated user. For example:

location, user,  state, -> destination 
/, no user                               -> a home page
/, user authenticated, state: unverified -> user profile page
/, user authenticated, state: verified   -> a content listing

What this looks like is that I am trying to 'route' based on the current user's state (as represented by a state machine). These 3 actions already exist in 3 different controllers (I call them 'pages', 'users', and 'posts'), but while one can call another controller's view, one can't call another controller's action, making it a little tough to not repeat myself. There's a number of ways to deal with this, but I'm not sure what The Rails Way is for this, so I thought I'd ask. I see as my options:

  • Use redirect_to in a hypothetical 'redirect controller', but I want the page to appear under /, so this isn't what I want.
  • Get fancy with a routing constraint (not sure this is possible; need sessions/cookies available in routing and I'm not sure that's the case)
  • Pull the logic for the particular actions out of their respective controllers, toss them into ApplicationController, and use them directly based on the user's state in a hypothetical controller (or just toss it into pages).
  • Repeat myself significantly, either in the controller, the views, or both
  • Yet-unknown options, I'm open to suggestions.

I'm leaning towards the third option, with the obvious downside that some piece of those controllers will now more or less inexplicably live in the ApplicationController (unless, god help me, I do some sort of Lovecraftian include-on-extend). Having this code live in two places feels dirty to me.

Am I missing something obvious?

Would a single action that uses a helper to pick the right partial based on the current state of the user work?

Also, take a look at using ActiveSupport::Concern instead of getting all Lovecraftian include-on-extend. http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM