Is there a way to generate the views separately using the rails generate command? I would also be willing to install a gem to accomplish that task f one exists. Basically the sc
As previously mentioned by sameers there was post that showed how to just generate a the views. It will create all the views for your model using the rails default templates which is very handy.
If like me you want something a little more customizable you can achieve the following.
You can create your own generator so you have something like this.
rails generate view NAME VIEW [options]
To achieve this you need to do the following.
rails generate generator view
This will generate a few files for you in lib/generators/view/ folder.
Open the view_generator.rb file and add the following code.
class ViewGenerator < Rails::Generators::Base
source_root File.expand_path('templates', __dir__)
argument :name, type: :string
argument :action, type: :string
def generate_view
template "#{file_name}.html.erb", "app/views/#{folder_name}/#{file_name}.html.erb"
end
private
def folder_name
name.underscore
end
def file_name
action.underscore
end
def type
name.titleize.singularize
end
def down_type
name.downcase.singularize
end
def render_form
"<%= render 'form', #{down_type}: @#{down_type} %>"
end
def render_link_back
"<%= link_to 'Back', #{folder_name}_path %>"
end
end
Next you need to create the file that we are using actual template used in generate_view method.
Using the action new as example, create a filelib/generators/view/new.html.erb and add the following.
New <%= type %>
<%= render_form %>
<%= render_link_back %>
Customize the template view as much as you want. You will need to add the _form.html.erb as well. Add any additional variables and logic in your view_generator.rb file and you are done.
It's more work but can be worth it if you find yourself generating similar views all the time.
Best use case I can think of for this approach is if you white label your platform and need to generate multiple files for a clients profile.