Rails: use image for a column in model - ruby-on-rails

I want users to be able to upload an image and have it be associated with a particular model. When I create my migration, what type do I use for my column? In the view I would like it to look something like this:
<%= form_for #person, :html => {:multipart => true} do |f| %>
<%= f.file_field :picture %>
<% end %>
Thanks guys :)

Probably :binary -- but, have you considered using something like Paperclip to handle image uploads for you? It can get really complicated otherwise.

I recommend the usage of an external plugin such as Paperclip or Carrierwave.

There's also the AWS-3 gem, if you just want cloud storage. I would think performance alone would be enough to not store an image in a DB.

Related

Is there a way to have multiple file uploads turn into multiple models

So I have a model called Photo and obviously I don't want to upload one photo at a time, so I replaced the new photo form with multi-file uploading. I am not quite sure how I can make these file uploads turn into unique photo models.
<%= bootstrap_form_with(:model => photo, :local => true) do |form| %>
<%= form.file_field :image, :multiple => true, :direct_upload => true %>
<%= form.submit %>
<% end %>
Edit: I am using Active Storage on Rails 6.0.0 rc2
You can't make multiple photo models. You probally mean multiple records. A model is a blueprint of the table in your database.
Check your terminal logs when you submit the form and you will probally see that in the params you will have something like: photo => [ files here ]
So in your controller create you have to loop through the array and create a photo record for each photo, something like this:
def create
params[:photo].each do |photo|
Photo.create(file: photo.file)
end
For those that come across this problem, here was my solution:
def create
photo_params[:images].each do |image|
#photo = current_user.photos.build
#photo.image = image
#photo.save
end
end

Direct Uploads to S3 using Carrierwave

I've recently converted the below from using Paperclip to Carrierwave uploading to Amazon S3 so I can make use of the carrierwave_direct gem and then Sidekiq or another background processing gem.
class Release < ActiveRecord::Base
has_many :releases_tracks, :dependent => :destroy
has_many :tracks, :through => :releases_tracks, :order => "releases_tracks.position DESC"
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :releases_tracks
end
class Track < ActiveRecord::Base
mount_uploader :track, TrackUploader
has_many :releases_tracks, :dependent => :destroy
has_many :releases, :through => :releases_tracks
end
/views/releases/track_upload.html.erb
<%= form_for(#release, :html => { :multipart => true }) do |f| %>
<h3>Upload Tracks for <%= #release.title %></h3>
<% index = 0 %>
<%= f.fields_for :tracks do |builder| %>
<%= #release.tracks[index].name %>
<%= f.file_field :track, :class => "file styled", :title => 'Select Track'%>
<% index += 1 %>
<% end %>
<%= f.submit "Upload Tracks", :class => "submit" %>
<% end %>
Carrierwave uploads are working, but I can't figure out how to get the direct part working. Partly because I can't figure out how to incorporate the suggested form code:
<%= direct_upload_form_for #uploader do |f| %>
<%= f.file_field :track %>
<%= f.submit %>
<% end %
Or the where in my track OR release controller I place the suggested:
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
The readme https://github.com/dwilkie/carrierwave_direct and Railscast http://railscasts.com/episodes/383-uploading-to-amazon-s3 both point towards uploading your file first and then creating your database entry. In my app the db entries already exist. The Railscast does say it's possible but doesn't go through it. So that's the first problem.
The second is that I need to upload more than one file at a time. The code above does achieve that, but very slowly and it of course renders my app pretty useless as it does so.
Can anyone help? Massive thanks in advance!
First of all I would advise you not to use carrierwave_direct, I really don't like this gem, for many reasons.
One of those reasons, is that as it's said in the docs
Please be aware that this gem only supports single
file uploads. If you want to upload multiple files simultaneously
you'll have to use a javascript or flash uploader.
But if you want to use it, here is what I guess you have to do :
So first about the
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
It seems you are trying to upload tracks, and as you said your models have already been created, I guess your are trying to upload new tracks for an existing release. Correct me if I'm wrong.
so you should create the #uploader var in the #track_upload method of your ReleasesController.
class ReleasesController
...
def track_update
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
end
...
end
then in the associated view (/views/releases/track_upload.html.erb), you can use the direct_upload_form
<%= direct_upload_form_for #uploader do |f| %>
<%= f.file_field :track %>
<%= f.submit %>
<% end %>
The form will upload the file directly to s3, just after you selected the file. Then I don't know exactly how, but carrierwave_direct should give you back the url of the uploaded file.
I'm not sure about that as I've never been that far with it, but the idea is that your file just got uploaded to s3, now it has to be linked to your model, so the file doesn't get 'lost'.
So maybe carrierwave_direct is doing things on its own (I doubt that ...) by doing some ajax requests or anything else.
Anyway as you want to upload more than one file, I'd like to point you to a tutorial I recently wrote
This shows how to upload files directly to s3, without carrierwave_direct, but by doing things on your own. This requires a little bit more code and time, but you have more control about what's happening.
In your case, you'll want to put the form I'm using in my tutorial in your view, in the /views/releases/track_upload.html.erb view.
Then once you'll select a file, the successful AJAX request(emitted by the jQueryFileUpload plugin) will give you the URL of the uploaded file so you can save it in your Track model (you'll probably want to emit a new AJAX request to your server to create the new Track model, or to populate an other form on the page, like the one you were using in the /views/releases/track_upload.html.erb file, and then the tracks will be saved on submit.)
I'm not sure I'm really clear about that, let me know if you need more explanations.
And the good thing about that is that if you simply add multiple to your file input, then the awesome jQueryFileUpload plugin will send a request per file to s3, then you'll get the URL's of the uploaded files in each ajax results :D
And you can tweak things to add progress bars, and things like that with the jQuery plugin, you can really create awesome things.
Hope it'll help you !

How do I access uploaded images in refinery cms?

I'm pretty sure that there should be an easy way of doing this. I already tried out to override the models and discovered that the imagines seem to get saved in the database.
All i want it to be able to show all the oploaded images in the application view, so that they can be displayed on every page.
Currently I am new to Rails, I would be thankful for an easy guide or at least some hints.
They're saved as Image model instances and you can use the image_fu view helper to render them in whatever size you need. So in your view just do something along the lines of
<% Image.all.each do |image| %>
<%= image_fu image, "100x100", :id => dom_id(image) %>
<% end %>

Problem with file uploads in a nested form using Rails3 with Mongoid and Carrierwave

Im having a problem transferring an SQLlite Rails 3 app over to a Mongoid Rails 3 app. In the SQLlite version, I am easily able to include an image upload form (using Paperclip) from one model ('image') within a nested form from another model ('product'). Here's my 'new' product form:
<%= form_for #product, :html => {:multipart => true} do |f| %>
<% f.fields_for :images do |image_form| %>
<%= f.label :productphoto %>
<%= f.file_field :productphoto %><br />
<% end %>
<% end %>
And here's the 'show' view:
<% #product.images.each do |image| %>
<%= image_tag image.productphoto.url(:gallerythumb) %><br />
<% end %>
When I try to use the same product views in my Mongoid Rails 3 app (using Carrierwave), I get the following error:
TypeError in Stores#show:
can't convert nil into String
<%= image_tag product.image.url(:gallerythumb) %>
Im pretty sure my models in the Mongoid version are correct because if I add a string (like 'name') to my 'image' model and nest that in the 'Product' form, it works. Also, Im able to upload an image into a non-nested model form.
Any help would be greatly appreciated!
I just had a similar problem myself. The problem is not the image upload I think, but the problem is that Rails doesn't recognize :images as being an Array. If you look into the Rails source of the fields_for helper you see that it checks for a method "_attributes=". If that's not there the form will be posted as normal fields and not as an array (params will be "images" instead of "images[0]")
You have to add the following line to your model:
accepts_nested_attributes_for :images
It is carrierwave or mongoid bug
https://github.com/jnicklas/carrierwave/issues#issue/81
This is most likely the issue that Lewy linked to -- that problem is specific to arrangements where your Carrierwave uploader is mounted on a child document in an embedded association and you are saving the parent, and though you don't explicitly show if this is how your data is modeled, I suspect that's the case since you noted that it works with a non-nested form (presumably saving the child document then, not the parent).
If you dig around in the discussions linked from that issue, you'll find some proposed workarounds. Here's what I ended up with to get Carrierwave working in this situation for me:
https://gist.github.com/759788
Full credit is to due to zerobearing2 whose gist I forked, I just made minor changes to get it working in Rails 3.0.3 and commented on my gist with summary info on the relevant discussions.

Populating a Select with Model Data in Rails

I feel the need to apologize for asking such a simplistic question, but I'm getting increasingly frustrated with the Rails Guides. I'm sure they answer my question, but they don't provide enough context for me to really understand how to apply what they're giving me. Nor is Google much help, though I may just be searching the wrong terms/phrases. Given that disclaimer, I'm just going to go ahead and ask:
I have an Image that HABTM Album. To support that, I have an albums_images table with image_id and album_id fields (no others). For the life of me, I can't figure out how to populate my image form partial so that the user can select the albums a newly uploaded image should belong to.
I'm learning Rails, so I really just want the basics. I'm sure there are fancy plugins to do this a hundred ways, but I'd like to learn the basics first and build from there. My form partial is pretty much textbook:
<% form_for( #image, :html => { :multipart => true } ) do |f| %>
# All the basics you'd expect to see.
<% end %>
My most recent attempt doesn't work any better than any other variation I've tried, but it looks like this:
<p>
<%= f.label :album_id %>
<%= f.select( :album_id, current_user.albums, :id, :name ) -%>
</p>
Again, I recognize the simplicity of the question I'm asking and I've read what I can find, but I haven't been able to put it together into a complete solution. There seem to be many ways to do it, but no real discussion of each one, their pros/cons or how to really use them in a larger context.
Thanks.
UPDATE: A couple of keys to note and a code correction. First, there's a HABTM relationship between images and albums. Neither model table has a FK directly referencing the other. Second, the album collection should be accessed as current_user.albums (corrected above). A user has_many albums and an album belongs_to user.
UPDATE: At the request of theIV below, at the moment, with this code:
22: <p>
23: <%= f.label :album_id %>
24: <%= f.select( :album_id, current_user.albums.collect {|a| [a.name, a.id]}) -%>
25: </p>
I get this error:
undefined method `album_id' for #<Image:0x1042ec110>
I get the error in line 24.
I think that select elements are one of the more confusing aspects of Rails, because as you said there seem to be a number of ways to do it.
Try this:
<%= f.select(:album_id, #image.albums.all.collect {|a| [a.name, a.id]}) -%>
Well, I'm not sure it's the best way, the Rails way or, frankly, even an elegant way, but here's the code I've used that seems to be working so far.
<%= f.label 'Albums' -%>
<%= collection_select( :image, :album_ids, current_user.albums, :id, :name, {}, { :multiple => true } ) -%>
At this point, when I say "working", all I can really attest to is that the page renders with no errors and the appropriate album or albums are selected when I edit an image. I'm still shocked at how difficult it was to cobble together a "full" solution from a lot of disparate sources.

Resources