Adding multiple assets to a resource with Rails - ruby-on-rails

I'm building a real-estate webapp, and every Ad should have an unlimited number of pictures (Asset).
In the Ad#new form I want to give the users the option to upload as many picture as they want.
I've created an Ad model which has_many Assets. An Asset is a model that holds a paperclip for a picture.
This is the code:
class Asset < ActiveRecord::Base
attr_accessible :picture
has_attached_file :picture, :styles => { :large => "600x600", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
belongs_to :ad
end
class Ad < ActiveRecord::Base
attr_accessible :contact_cell, :description, :price, :title, :user_id
belongs_to :user
has_many :assets, dependent: :destroy
end
How should the form_for look like if I want to give the user the option to add unlimited # of photos before he/she submits the form?

If you want to do it with html5, you can easily do it by doing something like (the main important thing to notice, is that on html5 you can add the attribute multiple=true, that will create a multiple upload for you):
<%= simple_form_for(#ad, html: { multipart: true }) do |f| %>
<%= f.input :contact_cell %>
<%= f.input :description %>
<%= f.input :price %>
<%= f.input :title %>
<%= file_field_tag('ad_assets_picture', multiple: true, name: "ad[assets_attributes][][picture]") %>
<%= f.button :submit %>
<%- end %>
otherwise you can just follow the nested form example, there is a nice webcast about it

Related

fields_for missing when trying to add accepts_nested_attributes_for

Im working on a simple form feature which adds an image via nested form.
Photo model which should store all of my uploaded images.
class Photo < ActiveRecord::Base
belongs_to :posting
has_attached_file :image, styles: { large: "500x500>", medium: "300x300>", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
snippet of my nested form (within a form)
<%= post.fields_for :photos, html: { multipart: true } do |photo| %>
<%= photo.label :image %>
<%= photo.file_field :image %>
<% end %>
Everything shows fine, but when I uncomment the accepts_nested_attributes_for line. My nested form disappears!
class Posting < ActiveRecord::Base
belongs_to :subcategory
belongs_to :category
has_many :photos
#accepts_nested_attributes_for :photos
end
I assume you assigned a #post instance variable in your PostsController's new action. You have to add the build_photo method to the new action:
def new
#post = Post.new
#post.build_photo
end
This should show your nested form, too.
See the One-to-many example in the API docs of fields_for
Untested, but this should be your solution.
<% post.photos.each do |photo| %>
<%= post.fields_for :photos, photo, html: { multipart: true } do |photo_fields| %>
<%= photo_fields.label :image %>
<%= photo_fields.file_field :image %>
<% end %>
<% end %>

How to make a file_field required before submit in erb Rails [duplicate]

This question already has answers here:
How to make a field required in Rails?
(2 answers)
Closed 7 years ago.
I'm trying to make a file_field required before the form is able to be submitted, using Rails and ERB, and I'm drawing a blank.
<%= form_for Image.new, html: {multipart: true} do |i| %>
<%= i.label :description %>
<%= i.text_field :description %>
<%= i.file_field :image %> <------**** This Line ****
<%= i.submit "Upload" %>
<% end %>
I've tried using 'required' in various ways and searched the web but to no avail. Is this something that I should seek to validate in the model instead?
My model is this:
class Image < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
belongs_to :user
has_attached_file :image, :styles => { :large => "600x600>", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
At the bottom of the list of suggested answers I found what I was looking for in this stack thread
validates :image, :presence => true
I simply had to add that to my model and it doesn't let the form submit without an image attachment.

Rails add separate view for child table

I'm creating a basic application where user has a profile and can upload upto 5 pictures of him/her.I created user profile page, I would want to allow the user to upload pictures in different page. Like having a link Add/Edit Photo and on clicking it to take to a different page and upon submit should redirect back to profile page and update/insert records. So I'm kind of confused should I do this under photos model/controller or member model/controller.Here is my sample code and link is below
I'm using paperclip for image upload
Member view
<%= link_to 'Add/Edit Photo' , edit_member_path(current_member.id) %>
<%= form_for(#member, :remote=> true, html: {
:multipart => true,
class:"form-light padding-15"}) do |f| %>
<%= f.label :firstname %>
<%= f.text_field :firstname, autofocus: true, :class => "form-control",:placeholder =>"FirstName" %>
<%= f.label :lastname %>
<%= f.text_field :lastname,autofocus: true, :class => "form-control",:placeholder =>"LastName"%>
<% end %>
class Member < ActiveRecord::Base
attr_accessible :firstname, :lastname, :user_id, :dob,:gender,:l_country_id,:age,
:l_state_id,:l_city,:g_country_id,:residency_status,:marital_status,
:community,:sub_community,:height,:weight,:complexion,:body_type,
:diet,:smoke,:drink,:education,:working_as,:working_with,:mobile_no,:about_yourself,:disability,:photos_attributes
has_many :photos
belongs_to :country
belongs_to :user
belongs_to :state
accepts_nested_attributes_for :photos
end
class Photo < ActiveRecord::Base
belongs_to :member
has_attached_file :data, :styles => { :thumb => "100x100#",
:medium => "500x500#",
:large => "700x700>" },
:url => "/assets/member/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/member/:id/:style/:basename.:extension"
#validates_attachment_presence :data
validates_attachment_content_type :data, :content_type => /\Aimage/
#validates_attachment_size :data, :less_than => 5.megabytes
validates_attachment_content_type :data, :content_type => ['image/jpeg', 'image/png']
attr_accessible :member_id,:data
end
As the separate pages are for photos only, my suggestion is to use PhotosController. And you can use nested resources to get the member_id from the url, if that is your concern.
http://guides.rubyonrails.org/routing.html#nested-resources

photo upload inside active_admin interface

I wan't to add image upload field inside active admin interface.This is the view where I want to be able get photo upload
I tried some earlier suggestions From here
ActiveAdmin.register Product do
form :html => { :multipart=>true } do |f|
f.inputs :new_product do
f.input :name
f.input :price
f.input :category
f.input :description
f.has_many :prod_images do |p|
p.input :photo, :as => :file, :label => "Image",:hint => p.template.image_tag(p.object.photo.url(:thumb))
p.input :_destroy, :as=>:boolean, :required => false, :label => 'Remove image'
end
end
f.buttons
end
Using this example I got such error
undefined method `klass' for nil:NilClass
It says that error is from here app/views/active_admin/resource/new.html.arb where line #1 raised
but how can I access that file, because in explorer it is not showing up?
Thanks
Try building a prod image, like this.
f.has_many :prod_images, f.object.prod_images.build do |p|
I managed to get file upload field with this code
ActiveAdmin.register Product do
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :photo, :as => :file, :hint => f.template.image_tag(f.object.photo.url(:thumb))
end
But now I can't add submit buttons :D So I am still working on it :)
EDIT
ActiveAdmin.register Product do
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :photo, :as => :file
f.buttons
end
end
This just shows buttons like Create and Cancel, but not showing up file field, I checked formastic examples, but without success.
EDIT2
class Product < ActiveRecord::Base
attr_accessible :category_id, :description, :manufacturer_id, :name, :photo
extend FriendlyId
has_attached_file :photo,
:styles => {
:thumb=> "100x100#",
:large => "290x170",
:medium=> "120x120"}
friendly_id :name, use: [:slugged, :history]
belongs_to :manufacturer
belongs_to :category
end

carrierwave + nested models: file_field not calling "create" method

I am trying to follow Railscast Ep 381 to integrate multi-file upload into my Rails app. For my app, the Projects model has many Steps, and Steps have many Images. The Image model is using a Carrierwave uploader.
Right now, I'm able to upload single image files from within the edit_steps path. But I'm trying to design the upload interface so that a gallery on the edit_steps page automatically refreshes once new images have been added (so once images have been selected but the form has not yet been submitted).
According to the Railscast episode, when you select images, they should automatically call the create action for each file. But my application is clearly not doing that. How can I ensure that the create method of the Image model is being called?
step.rb
class Step < ActiveRecord::Base
extend FriendlyId
friendly_id :number
attr_accessible :description, :name, :number, :project_id, :images_attributes
belongs_to :project
has_many :images
accepts_nested_attributes_for :images, :allow_destroy => :true
end
image.rb
class Image < ActiveRecord::Base
attr_accessible :project_id, :step_id, :file, :caption
belongs_to :step
belongs_to :project
mount_uploader :file, FileUploader
end
views/steps/edit.html.erb
%= semantic_form_for [#project, #step], :html => {:multipart => true} do |f| %>
<%= f.inputs do%>
....
<div id="images">
<%= render :partial => 'images/image', :collection => #step.images.all %>
</div>
<div class="clear"></div>
....
<%= f.fields_for :images, Image.new do |image_form| %>
<%= image_form.file_field :file, multiple: true, name: "image[file]"%>
<%end%>
javascript/images.js.coffee
jQuery ->
$('#new_image').fileupload
dataType: "script"
controllers/images.controller
def create
#image = Image.create(params[:image])
end
images/create.js.erb
<% if #image.new_record? %>
alert("Failed to upload image: <%= j #image.errors.full_messages.join(', ').html_safe %>");
<% else %>
alert("adding images")
$("#images").append("<%= j render(#image) %>");
<% end %>

Resources