在 Rails 5 中动态创建控制器操作
Dynamically creating controller actions in Rails 5
我正在尝试在 Rails 5.1.4 api 中设置动态路由。最初,我的所有动态路由都指向一个动作,效果很好。当我尝试使用 swagger-docs gem 时,问题就来了,它要求 ui 为每个条目重新执行一个单独的操作,以便为 swagger ui 生成必要的 json .所以,我想我可以简单地动态创建方法并将路由指向它们。据我所知,这些方法没有被创建,我不明白为什么。即使我将调试器放入循环遍历我的部分的循环中,它也永远不会被触发。我非常感谢对此的任何帮助。
routes.rb
Section.active.all.each do |section|
get "/#{section.url}", :to => "sections##{section.url}", defaults: { id: section.id }
end
sections_controller.rb
class SectionsController < ApplicationController
Section.active.all do |section|
define_method :"#{section.url}" do
#some things
end
end
end
development.rb
config.eager_load = true
如果我打电话:
SectionsController.action_methods
=> #<Set: {}>
我最后只是让 section_url 成为一个参数,将所有内容都指向 show 操作并在文档描述中添加可能的部分 url。
routes.rb
get "/:section_url", to: "sections#show"
#must be at the end of the routes definitions
sections_controller.rb
swagger_api :show do
summary "Returns Section Items"
param :path, :section_url, :string, :required, Section.active.pluck(:url).join(", ")
response :ok
response :not_found
end
我正在尝试在 Rails 5.1.4 api 中设置动态路由。最初,我的所有动态路由都指向一个动作,效果很好。当我尝试使用 swagger-docs gem 时,问题就来了,它要求 ui 为每个条目重新执行一个单独的操作,以便为 swagger ui 生成必要的 json .所以,我想我可以简单地动态创建方法并将路由指向它们。据我所知,这些方法没有被创建,我不明白为什么。即使我将调试器放入循环遍历我的部分的循环中,它也永远不会被触发。我非常感谢对此的任何帮助。
routes.rb
Section.active.all.each do |section|
get "/#{section.url}", :to => "sections##{section.url}", defaults: { id: section.id }
end
sections_controller.rb
class SectionsController < ApplicationController
Section.active.all do |section|
define_method :"#{section.url}" do
#some things
end
end
end
development.rb
config.eager_load = true
如果我打电话:
SectionsController.action_methods
=> #<Set: {}>
我最后只是让 section_url 成为一个参数,将所有内容都指向 show 操作并在文档描述中添加可能的部分 url。
routes.rb
get "/:section_url", to: "sections#show"
#must be at the end of the routes definitions
sections_controller.rb
swagger_api :show do
summary "Returns Section Items"
param :path, :section_url, :string, :required, Section.active.pluck(:url).join(", ")
response :ok
response :not_found
end