simple_formとStimulusを併用していて地味に詰まったポイント
:::message
この
TL;DR
- simple_formで
ケバブケースに 変換された data-targe t属性と、 Stimulusで targetを 参照する 際に 使用される 識別子の ミスマッチで targetが 参照できなくなっていた - simple_formは
属性名を HTMLに 合わせて スネークケースから ケバブケースに 変換してくれる - Stimulusで
識別子と して 登録されるのは Controllerの ファイル名=スネークケース
- simple_formは
- Stimulusの
Controller名が 2単語以上で 構成される 場合、 input_htmlで dat a属性の ハッシュではなく、 文字列で "data-controller_name-target"のように属性を 設定する 必要が ある
- input_html: {
- data: {
- "controller_name-target": "target",
- action: "change->controller_name#action"
- }
- }
+ input_html: {
+ "data-controller_name-target": "target",
+ data: { action: "change->controller_name#action" }
+ }
地味に詰まったポイント
Stimulusでは、
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
static targets = ['select'];
connect() {
// data-user_role-target属性値が"select"の要素が取得できる
this.selectTarget.doSomething();
// ...
}
}
Viewの
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.association :roles, collection: Role.all,
input_html: {
class: "select2 browser-default",
data: {
"user-role-target": "select",
action: "change->user_role#hoge"
}
}
%>
<%= f.button :submit %>
<% end %>
そこで
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.association :roles, collection: Role.all,
input_html: {
class: "select2 browser-default",
data: {
"user_role-target": "select",
action: "change->user_role#hoge"
}
}
%>
<%= f.button :submit %>
<% end %>
原因の
最終的に
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.association :roles, collection: Role.all,
input_html: {
class: "select2 browser-default",
"data-user_role-target": "select",
data: {
action: "change->user_role#hoge"
}
}
%>
<%= f.button :submit %>
<% end %>
補足
ちなみに
おわりに
明日は