Rails 7 + Turbo:turbo_stream は部分テンプレートの追加データで応答しますか?
概要
私はRails 7 + Turboをいじっていて、ユーザーリストのドロップダウンを持つフォームを作成しようとしています。フォームは新しい「ユニット」レコードを作成し、ユーザーをこのユニットに割り当てることができます。プランでは、ユニット レコードの所有者を検索して選択できるドロップダウンを作成します。問題は、ターボ ストリームが追加のデータ (コレクション) を返すことです。ネットワークリクエストを確認したところ、どうやらバックエンドがこのテンプレートに追加のデータを送信しているようです。この追加データなしで応答を作成し、部分的なテンプレートのみを返すにはどうすればよいですか?
追加のデータ
[#<User id: 4, email: "[email protected]", created_at: "2022-03-18 13:29:04.813660000 +0000", updated_at: "2022-03-18 13:29:19.397311000 +0000", first_name: nil, last_name: nil, phone: nil, meta: {}, account_id: 2>]
これが完全な応答です。
<turbo-stream action="update" target="owner_search_result"><template>
<li
id=user_4
class="hover:bg-blue-600 relative select-none py-2 pl-3 pr-9 text-gray-900 cursor-pointer" id="option-0"
role="option" tabindex="-1">
<span class="block truncate">
</span>
<span class="absolute inset-y-0 right-0 flex items-center pr-4 text-indigo-600">
<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd" />
</svg>
</span>
<span class="ml-2 truncate text-gray-500">
[email protected]
</span>
</li>
[#<User id: 4, email: "[email protected]", created_at: "2022-03-18 13:29:04.813660000 +0000", updated_at: "2022-03-18 13:29:19.397311000 +0000", first_name: nil, last_name: nil, phone: nil, meta: {}, account_id: 2>]</template></turbo-stream>
これはユーザーコントローラーです
def search
keyword = user_params[:keyword] || ""
@users = User.filter_by_email(keyword)
respond_to do |format|
format.turbo_stream do
render turbo_stream: turbo_stream.update(:owner_search_result, partial: 'users/unit_owner', locals: { users: @users })
end
end
end
部分的なものはこれです
<%= @users.each do |user| %>
<li
id=<%= dom_id(user) %>
class="hover:bg-blue-600 relative select-none py-2 pl-3 pr-9 text-gray-900 cursor-pointer" id="option-0"
role="option" tabindex="-1">
<span class="block truncate">
<%= user.first_name %>
<%= user.last_name %>
</span>
<span class="absolute inset-y-0 right-0 flex items-center pr-4 text-indigo-600">
<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd" />
</svg>
</span>
<span class="ml-2 truncate text-gray-500">
<%= user.email %>
</span>
</li>
<% end %>
どうもありがとう。
解決策
交換する
<%= @users.each do |user| %>
部分的な先頭に
<% @users.each do |user| %>
各呼び出しの戻り値、つまりイテレータ自体をビューにレンダリングしたくないからです。 = を削除する必要があることに注意してください。