When I use rails g scaffold Model key:string value:string
command it creates both controller and views (erb, scss, js). How can I generate only controller which will respond with only JSON format.
Asked
Active
Viewed 4,757 times
9

kleverigheid
- 111
- 1
- 5
-
How can I do this? If I skip assets controller will be for JSON only (as I know it will have HTML also)? – kleverigheid Mar 16 '16 at 18:47
3 Answers
13
Use API flag in Rails 5+
Without having to modify configuration:
rails g scaffold TestLink --api
Pro tip: Use the --pretend flag to see what will be created before running:
rails g scaffold TestLink --api --pretend

Matt
- 5,800
- 1
- 44
- 40
4
If you already have a project setup as a normal rails app, you can make the generators api only by setting it up in config/application.rb
.
config.generators do |g|
g.api_only = true
end

Cereal
- 3,699
- 2
- 23
- 36
2
To change the Rails controller generated by the scaffold you can add a new file: lib/templates/rails/scaffold_controller/controller.rb
. It might be helpful to copy the template from the Rails source code as a starting point. From there you can edit each of the actions to end with render json
, for example:
# GET <%= route_url %>
def index
@<%= plural_table_name %> = <%= orm_class.all(class_name) %>
render json: @<%= plural_table_name %>.to_json
end
To prevent asset/view files from being generated, add this to your config/application.rb
file:
module AppName
class Application < Rails::Application
# comments and config
# ...
config.generators do |g|
g.stylesheets false
g.javascripts false
g.helper false
g.views false
end
end
end

Shaun
- 2,012
- 20
- 44