Rails7有很大的改动。其中影响最大的一个就是Hotwire
config/application.rb
中改为config.load_defaults 7.0
才会采用Rails7的默认值。
可以把webpacker相关的内容全部删除了,新的东西可以在rails7中生成一个新的project,相应的拷贝过来。
app/javascripts
只需要application.js,删除其他所有。增加controller目录。注意该目录下需要application.js,否则js报错不能正常工作,我卡在这里好久。
Gemfile中
# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"
# remove webpacker
gem 'webpacker', '~> 4.0'
Gemfile中
# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"
# remove
# gem 'turbolinks', '~> 5'
# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"
需要的改动
+ 查询所有turbolinks地方,替换为turbo。如把所有 HTML 的 data 属性的data-turbolinks更新为data-turbo。turbolinks:load -> turbo:load
+ link_to data: :delete|post
-> data: {turbo_method: :delete|post}
+ confirm message: data: { confirm: 'Are you sure?' }
-> data:{turbo_confirm: 'Are you sure?'}
. Together: data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'},
+ method works for button_to
# link_to works
<%= link_to t('destroy'), offered_path(@offered), data: {turbo_method: :delete, turbo_confirm: 'Are you sure??'} %>
# not working, still post method.
<%= button_to t('destroy'), offered_path(@offered), data: {turbo_method: :delete, turbo_confirm: 'Are you sure??'} %>
# works
<%= button_to t('destroy'), offered_path(@offered), method: :delete, data: {turbo_confirm: 'Are you sure??'} %>
# confirm not work
<%= button_to t('destroy'), offered_path(@offered), method: :delete, confirm: 'Are you sure??' %>
ruby
# not work
<%= link_to t("download"), link, data: { turbo_confirm: 'sure'} %>
# works, 注意,如果设置了data-turbo=false,则不work
<%= link_to t("download"), link, data: { turbo_method: :get, turbo_confirm:'sure?'}%>
# works
<%= button_to t("download"), link, data: { turbo_method: :get, turbo_confirm: 'sure?'} %>
+ controller中render需要增加status,否则有Form responses must redirect to another location
错误 例如
format.html { render :signup } =>
format.html { render :signup, status: :unprocessable_entity}
+ 出错后render自身页面,需要增加redirect_to
format.html { flash[:error] = "ERROR" } =>
format.html { flash[:error] = "ERROR"; redirect_to({action: :login})}
The "default" rails way to do things that I usually see is:
submit a form
redirect on success
render html on error
As such, since Turbo currently requires redirects on all forms, it's a major blocker to prevent folks switching over.
app/assets/config/manifset.js
用于配置需要编译的静态内容。典型配置如
/* Sprockets config, static resources to be compiled */
//= link_tree ../images
//= link_directory ../stylesheets .css
//= link_tree ../../javascript .js
//= link_tree ../../../vendor/javascript .js