CarrierWave and nested forms retain an empty image object if photo: caption is included in the form

I am after some advice regarding the processing of embedded form data, and I would always be grateful for any ideas.

The problem is that I am not 100% sure why I need the following code in my model

  accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? }

I do not understand why I need to click on my accepts_nested_attributes_for association:

:reject_if => lambda { |a| a[:title].blank? }

If I delete this: reject_if lambda, it will save the empty holiday photo object in the database. I guess because it takes a: title field from the form as an empty string?

I suppose my question is, am I doing it right or is there a better way of doing this inside nested forms if I want to extend my HolidayImage model to include more lines like description, notes?

Sorry if I cannot be more concise.

A simple application for relaxation.

# 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

I use CarrierWave to upload images.

# holiday_image.rb 
class HolidayImage < ActiveRecord::Base
  belongs_to :holiday
  attr_accessible :holiday_id, :image, :title

  mount_uploader :image, ImageUploader
end

Inside the partial _form there is a field_for field

<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 %>

Thanks again for your patience.

+5
source share
1 answer

accepts_nested_attributes_forusually used to create children during mass assignment (when creating a new record, creating any related models). For example, if you have a type model User, which has_many UserPhotos, you can take several UserPhotosat creation time Userand create them all based on User.

, , (ImageUploader) (HolidayImage). HolidayImage , :image, CarrierWave ImageUploader.

, , :

  • validates_presence_of :image, :image. , present?, API (. Wear Wrier Wiki ActiveRecord). , , , , , . , .

  • before_save, , , CarrierWave, . image.present? image_changed? , HolidayImage. . CarrierWave .

  • , . CarrierWave How accept_nested_attributes_for.

+1

All Articles