Rails: Photo uploads (Paperclip) with nesting & strong params -
background:
i'm trying add photo uploads advert model using strong params paperclip gem, photo separate model "has_attached_file" :upload, , calling forms_for (actually semantic_forms_for i'm using formtastic) in ads#new view upload image photo instance. params looks ok think i've missed in controller. haven't been able working despite multiple iterations of controller code. need differently working?
would appreciate tips or pointers! thank you
--
ad model:
class ad < activerecord::base belongs_to :user ##edited out irrelevant associations has_many :photos, dependent: :destroy accepts_nested_attributes_for :photos, :allow_destroy => true default_scope { order("created_at desc") } #validates_presence_of :user_id, :make, :model, :km, :year, :location end
--
photo model:
class photo < activerecord::base belongs_to :ad has_attached_file :upload, :styles => { :main => "600x500>", :thumb => "60x45>" }, :default_url => "http://placehold.it/600x500&text=nice+wheels!" end
adscontroller
class adscontroller < applicationcontroller def create @ad = ad.new(ad_params) @ad.user_id = current_user.id @photo = @ad.photos.build if @ad.save redirect_to @ad else flash.alert="you missing super-important details. try again" redirect_to new_ad_path end end private def ad_params ##excluded attributes except nested upload attrib. gist params.require(:ad).permit(photos_attributes: [upload: [:upload_file_name, :upload_content_type]]) end end
ads#new
<%= semantic_form_for @ad |form| %> <!-- left out other form fields --> <%= form.semantic_fields_for :photo |photo| %> <%= photo.file_field :upload %> <% end %> <% end %>
ad params hash after submit action (ad#create)
{"location":"abha","make":"bentley","model":"","gear":"","km":"50","price_bid":"500","price_ask":"500","ac":"0","cd":"0","radio":"0","powersteering":"0","abs":"0","satnav":"0","cruise":"0","fwd":"0","convertible":"0","problem_1":"","problem_2":"","problem_3":"","description":"","photo":{"upload":{"original_filename":"mustang-290x218.jpg","content_type":"image/jpeg","headers":"content-disposition: form-data; name=\"ad[photo][upload]\"; filename=\"mustang-290x218.jpg\"\r\ncontent-type: image/jpeg\r\n","tempfile":[]}}}
routes
resources :ads, only: [:new, :create, :show, :index, :edit, :destroy] resources :comments, only: [:create, :destroy] resources :photos, only: [:create, :destroy] resources :favorite_ads, only: [:create, :destroy] resource :emails, only: :create end
the form needs specified multi-part file uploads work:
<%= semantic_form_for @ad, :html => {:multipart => true} |form| %>
in addition, aren't permitting tempfile passed:
params.require(:ad). permit(photos_attributes: [upload: [:upload_file_name, :upload_content_type, :tempfile] ])
Comments
Post a Comment