この has_many :through collection_check_boxes フォーム入力ではレコードが正しく作成されないのはなぜですか?
概要
Rails 7アプリに has_many :through 関連付け設定があります。
イベントの予約を処理するために ActsAsBookable gem を使用しています。イベントには予約から追加できる_many 個の EventExtras があり、予約には_many 個の SelectedExtras があります。 ActsAsBookable gem のせいで、少しだけ複雑さが追加されます。
コード例を関連部分まで切り詰めます
module BookingMonkeyPatch
extend ActiveSupport::Concern
included do
has_many :selected_extras, foreign_key: "acts_as_bookable_booking_id", dependent: :destroy
has_many :event_extras, through: :selected_extras
belongs_to :booking_set, optional: true
end
end
ActsAsBookable::Booking.include(BookingMonkeyPatch)
class EventExtra < ApplicationRecord
belongs_to :event
has_many :selected_extras
has_many :acts_as_bookable_bookings, through: :selected_extras, class_name: "ActsAsBookable::Booking", foreign_key: "acts_as_bookable_booking_id"
end
class SelectedExtra < ApplicationRecord
belongs_to :event_extra
belongs_to :acts_as_bookable_booking, foreign_key: "acts_as_bookable_booking_id", class_name: "ActsAsBookable::Booking"
end
class Event < ApplicationRecord
has_many :event_extras, dependent: :destroy
end
class BookingSet < ApplicationRecord
has_many :acts_as_bookable_bookings, class_name: "ActsAsBookable::Booking", foreign_key: "booking_set_id"
end
私のフォームでは次のものを使用しています。
<%= simple_form_for @booking_set, data: {turbo: "false"} do |form| %>
<%= form.input :user_id, as: :hidden, input_html: { value: @user.id } %>
<%= form.simple_fields_for :acts_as_bookable_bookings do |booking_subform| %>
<%= render 'acts_as_bookable_booking_fields', f: booking_subform %>
<% end %>
<%= link_to_add_fields "Add Another Booking", form, :acts_as_bookable_bookings, "build_shoot" if @bookers&.size > 1 %>
<% end %>
そして、ネストされたフォーム内には次のようになります。
<%= f.collection_check_boxes :event_extra_ids, @selected_event.event_extras, :id, :name, {}, { :multiple => true } %>
これはうまくいきます。このフォームはさらに 2 レベル下にネストされており、すべてのネストは正常に機能します。私が抱えている問題は、エクストラの 1 つを選択してフォームを送信しようとすると、基本的に SelectedExtra を作成するには act_as_bookable_booking_id が必要であるという検証エラーが発生することです。
これはある意味、私にとっては理にかなっています。送信されたパラメータを見ると、event_extra_ids => {“24”, “25”} だけです。 SelectedExtra を作成するには、選択した追加の予約が何であるかを知る必要もあります。 collection_select または collection_check_boxes は、他の提案のようにこれを自動的に処理すると思いましたが、機能しないようです。
ここで間違っている点はありますか?
解決策
accepts_nested_attributes_for がモデルで定義されていないようです…「RoR ガイド: 複雑なフォームの構築」を参照してください。
それ以上の問題がある場合は、<%= render ‘acts_as_bookable_booking_fields’, f: Booking_subform %> をコメント アウトし、一時的に ‘acts_as_bookable_booking_fields’ 内の内容に置き換えて、フォーム構造の問題であるか、問題であるかどうかのトラブルシューティングをより簡単にします。巣作り。