Skip to content

Instantly share code, notes, and snippets.

@radar
Created January 5, 2014 22:56
Show Gist options
  • Save radar/8275187 to your computer and use it in GitHub Desktop.
Save radar/8275187 to your computer and use it in GitHub Desktop.
class ContentBlock < ActiveRecord::Base
belongs_to :parent, polymorphic: true
has_one :text_block, dependent: :destroy
accepts_nested_attributes_for :text_block
has_one :image_block, dependent: :destroy
accepts_nested_attributes_for :image_block, reject_if: :attachment_not_updated
def attachment_not_updated(params)
if params['image_attributes']['attachment'].blank?
params['image_attributes'].delete
end
false
end
end
<%= content_block_field.fields_for :image_block do |field| %>
<%= image_tag(field.object.image.attachment_url) if field.object.image %>
<div class="field">
<%= field.text_field :title, placeholder: 'Title (optional)' %>
</div>
<div class="field">
<%= field.text_area :caption, placeholder: 'Caption (optional)' %>
</div>
<div class="field">
<%= field.fields_for :image do |image| %>
<%= image.file_field :attachment %>
<% end %>
</div>
<% end %>
class ImageBlock < ActiveRecord::Base
belongs_to :content_block
has_one :image, as: :parent, dependent: :destroy
accepts_nested_attributes_for :image
end
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LbWRzAzsuhs3Zaqg0BoOHzVQr6Qc0Om1prVMph7K2bI=", "section"=>{"title"=>"About", "position"=>"1", "active"=>"1", "content_blocks_attributes"=>{"0"=>{"parent_type"=>"Section", "parent_id"=>"1", "block_type"=>"ImageBlock", "position"=>"1", "_destroy"=>"false", "image_block_attributes"=>{"title"=>"first image title", "caption"=>"first image caption", "image_attributes"=>{"id"=>"34"}, "id"=>"41"}, "id"=>"12"}, "1"=>{"parent_type"=>"Section", "parent_id"=>"1", "block_type"=>"ImageBlock", "position"=>"2", "_destroy"=>"false", "image_block_attributes"=>{"title"=>"second image title", "caption"=>"second image caption", "image_attributes"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x007fbe6c648610 @tempfile=#<Tempfile:/var/folders/gm/2s4tl74s2sq_b353yjj5g2l00000gn/T/RackMultipart20140105-61223-1oiras8>, @original_filename="photo 2.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"section[content_blocks_attributes][1][image_block_attributes][image_attributes][attachment]\"; filename=\"photo 2.JPG\"\r\nContent-Type: image/jpeg\r\n">, "id"=>"35"}, "id"=>"42"}, "id"=>"14"}}}, "id"=>"1"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment