I'm trying to customize my scaffold generator, and I would like to have a new partial for the view in the same directory, in particular _item
to be called both inside index and show. I can get all the templates but I'm not able to generate this file through
rails g scaffold foo name:string
I tried to put _item.erb in /lib/templates/erb/scaffold/
(together with the other files) but it is ignored- Does anybody have a clue?
I use ruby on rails 3, but please let me know if the solution is valid for rails 2 as well. I also use simple_form (thus I already have the _form partial), but I think the solution should be valid even without it.
I came across this question hoping to find an answer as the default rails scaffold generator is pretty crippled if you want to:
Alas, I rolled up my sleeves and figured out how to make rails scaffold generator support the above requirements which I make use of on my current project.
If you want full control over your scaffold templates when you type
rails g scaffold Foo ...
then read on!The Problem
The default rails scaffold generator is template engine specific AND hard codes a fixed set of view files that it looks for.
The Solution
Use a custom generator and wire it up to the scaffold template generation.
I have included a generator below that looks in
lib/templates/scaffold
and will generate scaffold views for ALL files found there including templates, partials and sub-directories regardless of the template engine.IMO this should be the default rails behaviour instead of us having to jump through hoops like this..
Implementation
Do the following:
lib/templates/scaffold
. Notice there is noerb
subdirectory !!Rails 4 generator configuration:
Rails 3 generator configuration:
The custom scaffold generator:
Caveats
No warranty offered :)
I hope this helps others who want to refactor their scaffold views with partials and support multiple template engines.
I believe this is hardcoded into scaffold g. What I did was to create a rake task that adds more files.
Just found it.
It is hardcoded. You can change it:
https://github.com/rails/rails/blob/master/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb
In my index template I did like this:
Then, just created a rake task that reads that comment and create the new files.
Ugly but effective.