[Rails] 修改預設的 scaffold 模板
修改 model
app/lib/templates/active_record/model/model.rb 官方範例
修改 view
app/lib/templates/scaffold/_form.html.erb app/lib/templates/scaffold/edit.html.erb app/lib/templates/scaffold/index.html.erb app/lib/templates/scaffold/new.html.erb app/lib/templates/scaffold/show.html.erb 官方範例
修改 controller
app/lib/scaffold_controller/controller.rb 官方範例
修改 rspec
app/lib/templates/rspec/scaffold/controller_spec.rb 官方範例
寫法
<%% %>
代表可以產生rails語法
在裡面可以塞 <% %>
變數 語法
例如:
<%%= link_to 'edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %>
最後產生的 template 會是
<%= link_to 'edit', edit_user_path(user) %>
變數整理
假設 rails g scaffold System::ModelName attr1 attr2
application_name: my_app
attributes_names: ["attr1", "attr2"]
class_path: ["system"]
regular_class_path: ["system"]
singular_name: model_name
plural_name: model_names
human_name: Model name
plural_file_name: model_names
fixture_file_name: model_names
class_name: System::ModelName
file_path: system/model_name
i18n_scope: system.model_name
model_resource_name: system_model_name
singular_route_name: system_model_name
singular_table_name: system_model_name
plural_route_name: system_model_names
plural_table_name: system_model_names
table_name: system_model_names
redirect_resource_name: @system_model_name
route_url: /system/model_names
url_helper_prefix: system_model_name
index_helper: system_model_names
new_helper: new_system_model_name_url
edit_helper: edit_system_model_name_url(@system_model_name)
show_helper: system_model_name_url(@system_model_name)
故障排除
Q1. 調整後產生scaffold,但是模板沒變
Ans.: 須先執行 spring stop
再產生scaffold
參考
- https://api.rubyonrails.org/classes/Rails/Generators/NamedBase.html#method-i-application_name
留言