Auto-generate routes for scaffolded controller in Rails 4?

[亡魂溺海] 提交于 2019-12-10 19:58:58

问题


I'm trying to get a quick-and-dirty Ajax UI going for an app that already has its data model well in hand - it's basically been managed via rails console so far. Anyway, I thought I would start by auto-generating the missing controller logic that you would get from a rails g scaffold, only instead with rails g scaffold_controller for an existing controller.

It created the controller, and the views, and the assets.. but it didn't touch the routes at all! It didn't even try, didn't say "warning: routes.rb has been modified, not changing" or anything like that, and there's no mention of routes at all in the help output of rails g scaffold_controller.

So how do I say "Just give me the normal routes you would have given me if I started from scratch, please!"?


回答1:


If I understand the question:

Please, open the config/routes.rb file, and inside the block (routes.draw) add the resources method with the table name (plural of model) as param. Like this:

MyApp::Application.routes.draw do
  resources :products
  ... # rest of code
end

That define the routes for RESTful actions over products. You can read more here

At the console you can run: rake routes to see the available routes at your app.




回答2:


Although this is asking about Rails 4 for long time ago, but with Rails 5, rails g scaffold_controller still won't auto-generate route, I did it with below monkey patch:

require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'

patcher = Module.new do
  extend ActiveSupport::Concern

  included do
    hook_for :resource_route, required: true
  end
end

Rails::Generators::ScaffoldControllerGenerator.send :include, patcher


来源:https://stackoverflow.com/questions/26568714/auto-generate-routes-for-scaffolded-controller-in-rails-4

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