ネストされたフォーム データの処理に関するアドバイスを求めています。洞察に感謝します。
問題は、モデルで次のコードが必要な理由が 100% わからないことです。
accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? }
私がaccepts_nested_attributes_forアソシエーションに触れる必要がある理由がわかりません:
:reject_if => lambda { |a| a[:title].blank? }
この :reject_if ラムダを削除すると、空の休日の写真オブジェクトがデータベースに保存されます。フォームから :title フィールドを空の文字列として取得するためだと思いますか?
私の質問は、HolidayImage モデルを拡張して説明やメモなどの文字列をさらに含めたい場合、これを正しく行っているか、ネストされたフォーム内でより良い方法があるかということだと思います。
もっと簡潔に言えなかったらごめんなさい。
私のシンプルな休日アプリ。
# holiday.rb
class Holiday < ActiveRecord::Base
has_many :holiday_image
accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? }
attr_accessible :name, :content, :holiday_image_attributes
end
画像のアップロードには CarrierWave を使用しています。
# holiday_image.rb
class HolidayImage < ActiveRecord::Base
belongs_to :holiday
attr_accessible :holiday_id, :image, :title
mount_uploader :image, ImageUploader
end
私の _form パーシャル内には、field_for ブロックがあります
<h3>Photo gallery</h3>
<%= f.fields_for :holiday_image do |holiday_image| %>
<% if holiday_image.object.new_record? %>
<%= holiday_image.label :title, "Image Title" %>
<%= holiday_image.text_field :title %>
<%= holiday_image.file_field :image %>
<% else %>
Title: <%= holiday_image.object.title %>
<%= image_tag(holiday_image.object.image.url(:thumb)) %>
Tick to delete: <%= holiday_image.check_box :_destroy %>
<% end %>
ご辛抱いただきありがとうございました。