可以将自定义约束路由到多个控制器操作?

问题描述:

目前我使用的是被链接到像一个单一的路径的自定义约束:可以将自定义约束路由到多个控制器操作?

get '/hello', to: 'account#index', 
     constraints: AccountConstraint.new 

基本上我的自定义约束仰视request.host,并且如果在数据库中找到匹配项?方法将返回true,然后帐户#索引操作将被调用。

我想要做的是,如果约束匹配,那么基于路径将执行不同的操作。

所以我的约束是这样的:

class AccountConstraint 
    def matches?(request) 
    # lookup the database, return true if record found 
    end 
end 

然后我想我route.rb文件做这样的事情(伪代码below_:

if AccountConstraint matches 
    get '/', to: "account#index" 
    get '/hello', to: "account#hello" 
end 

是这样的可能吗?如果是这样,怎么样?

+0

我会在控制器内写入那种逻辑,而不是在路由文件中。您可以检查控制器,如果请求匹配,甚至在视图中。 –

+0

你应该使用控制器从控制器中的请求中检查引用者/主机,而不是路由并相应地重定向...它会好得多。 – Mayank

我不知道我是否理解这个问题,但它听起来像你想要的是一个scope

scope constraints: AccountConstraint.new do 
    get '/', to: "account#index" 
    get '/hello', to: "account#hello" 
end 

只有在AccountConstraint匹配的情况下,才能访问范围内的路由。