Rails 3 routing based on context

强颜欢笑 提交于 2019-12-05 10:27:29

I finally found a solution to my problem that I like. This will use the URLs from my original question.

First, assume a session-stored Context object that stores whether the user is in a "user" context or a "company" context. If the user is in a "company" context, then the ID of the company they're working as is in the object as well. We can get the context via a helper named get_context and we can get the currently logged-in user via current_user.

Now, we set up our routes as so:

config/routes.rb:

MyApplication::Application.routes.draw do
  get "dashboard" => "redirect", :user => "/users/show", :company => "/companies/:id/dashboard"
end

Now, app/controllers/redirect_controller.rb:

class RedirectController < ApplicationController
  def method_missing(method, *args)
    user_url    = params[:user]
    company_url = params[:company]
    context     = get_context

    case context.type
    when :user
      redirect_to user_url.gsub(":id", current_user.id.to_s)
    when :company
      redirect_to company_url.gsub(":id", context.id.to_s)
    end
  end
end

It's easy enough to keep the actual URLs for the redirect where they belong (in the routes.rb file!) and that data is passed in to a DRY controller. I can even pass in the ID of the current context object in the route.

Your approach seems like the best way to me. Anything else would be more cluttered and not very standard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!