[英]Rails 4 Dynamic Controller in routes
I am creating a rails api, and am attempting to keep a modular approach in my controller. 我正在创建一个Rails api,并试图在我的控制器中保持模块化方法。 As such, I have a few models - Organization
, Branch
, User
. 因此,我有一些模型Organization
, Branch
, User
。 Let's say that Users belong_to Organization
, and Branches belong_to Organization
. 假设Users belong_to Organization
, Branches belong_to Organization
。
In a base controller that all other controllers extend, I want to have an index
method that knows how to handle a few different routes: 在所有其他控制器都扩展的基本控制器中,我想拥有一个index
方法,该方法知道如何处理一些不同的路由:
Organizations/1/branches
and Organizations/1/users
. Organizations/1/branches
和Organizations/1/users
。
That index method would be more beefy than the following, but this is the idea: 该索引方法将比以下方法更为强大,但这就是这个主意:
def index
Organization.joins(params[:relation_one].to_sym).where(id: params[:organization_id])
end
And my routes would be defined like so: 我的路线将这样定义:
scope '/organizations' do
scope '/:organization_id' do
get '/' => 'organizations#show'
put '/' => 'organizations#update'
scope '/:relation_one' do
get '/' => ':relation_one#index'
post '/' => ':relation_one#create'
scope '/:relation_one_id' do
get '/' => ':relation_one#show'
put '/' => ':relation_one#update'
end
end
end
end
How can I create dynamic routes similar to above in which the controller is dynamic based on the url route? 如何创建与上述类似的动态路由,其中控制器基于url路由是动态的? Something similar to the above snippet should work for both Organizations/1/branches
and Organizations/1/users
without me specifically defining both routes. 在没有我专门定义这两种路线的情况下,与以上代码段相似的内容应适用于Organizations/1/branches
和Organizations/1/users
。 This API will have several relations like this down the road, so I want to come up with the right approach now. 这个API将来会有几种类似的关系,所以我现在想提出正确的方法。
you could write up an array of the controller names and then run a loop in routes.rb 您可以编写一个控制器名称数组,然后在routes.rb中运行循环
relations = [':relation_one', ':relation_two']
scope '/organizations' do
scope '/:organization_id' do
get '/' => 'organizations#show'
put '/' => 'organizations#update'
relations.each do |rel|
scope "/#{rel}" do
get '/' => "#{rel}#index"
post '/' => "#{rel}#create"
scope "/#{rel}_id" do
get '/' => "#{rel}#show"
put '/' => "#{rel}#update"
end
end
end
end
end
you could create a constant that stores all controllers you want to have in an array and then just iterate through in your routes file 您可以创建一个常数,将要存储的所有控制器存储在一个数组中,然后在您的路由文件中进行迭代
AVAILABLE_CONTROLLERS = [:organizations, :branches, :users]
AVAILABLE_CONTROLLERS.each do |cname|
scope "/#{cname}" do
scope '/:id' do
get '/', :action => :show
put '/', :action => :update
scope '/:relation_one' do
get '/' => ':relation_one#index'
post '/' => ':relation_one#create'
scope '/:relation_one_id' do
get '/' => ':relation_one#show'
put '/' => ':relation_one#update'
end
end
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.