CarrierWave and nested forms saving empty image object if photo :title is included in form

Posted by Wasabi Developer on Stack Overflow See other posts from Stack Overflow or by Wasabi Developer
Published on 2012-06-20T14:40:38Z Indexed on 2012/06/20 15:16 UTC
Read the original article Hit count: 254

Filed under:
|
|

I'm after some advice in regards to handling nested form data and I would be ever so grateful for any insights.

The trouble is I'm not 100% sure why I require the following code in my model

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

If I don't understand why I require to tact on on my accepts_nested_attributes_for association:

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

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

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

Sorry If I can't be more succinct.

My simple holiday app.

# 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'm using CarrierWave for image uploads.

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

  mount_uploader :image, ImageUploader
end

Inside my _form partial there is a field_for block

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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby