Rails 5.2 ActiveStorage Introduction

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's up guys this episode we're diving into active storage and rails 5.2 and this feature is very welcome because file uploading is something we've had to rely on third-party gems for but it's such a common feature to upload files to your rails app that it is now finally baked into rails core so we're gonna be talking about that and if you've ever used paperclip or carrier wave or shrine it's all very similar and you don't have any real reason to upgrade if you're happy with those but if you're building a new application and you want to use this go for it it is really really well integrated into rails but it's still got a bit of rough edges and there will be some things that will certainly improve in the next few releases I'm sure so let's dive in just setting this up and taking a look at how it all works so basically when you create a rails 5.2 application you can run rails active storage : install to create the migration to add active storages to tables to your application if you upgrade from rails 5 1 or 4 whatever to 5 2 you can run this to get those migrations as well so if you run this command if you're already got the migration it's not going to do anything which I do and that migration looks like this it's going to create two tables one called blobs one called attachments and the blobs are going to stall store all the metadata around a file that you uploaded like the file name file size content type all that good stuff and then the attachments is the join table between your models whatever they might be and the uploads that you created so that's going to be as simple as it is they keep track of that and the reason this is great is because it means that you don't have to create migrations whenever you want to add a new upload to your model so you might want to add avatars or you know uploads to a post or attachments or images or any of that stuff you don't have to make anymore migrations or anything like that no more database changes when you want to add new file uploads and that is really nifty so this is something that I think is really pretty well designed and really makes it handy to go add file uploads so we can go to you know a model like user and simply say it has one attached avatar and you are good to go that's going to set up the methods and the associations so that when you upload an avatar on a user it will go ahead and create the attachment record and the blob records in the database and that's kind of awesome so let's take a look at an example of what you have to do to set this up going forward so first off you have to go to config environments development and production and look for the active storage service line if you created new rails 5.2 app or add this line if you upgraded to rails 5.2 and you're gonna set this to the key in your config storage gamal file now this is where you will have your defined locations of file uploads so I've got a few examples in here by default you'll only get tested local because they don't know your credentials for AWS they don't know if you even want to use AWS s3 to upload files to so the defaults are of course to upload to your current machines file system wherever rails is living so that is pretty straightforward and that's good in development and test but in production you probably want to go to s3 digital ocean spaces Google Cloud Storage is sure or something else and these are the main options that you have right now you have s3 you can use digital ocean spaces because it's fully compatible with s3 you can use Google Cloud storage or Microsoft Azure and you also have a suite mirror service for redundancy so you can have your files uploaded to two or three of those services at the same time and that will take care of any mirroring that you might want to do so I would definitely encourage that if you want redundancy and you just basically set up two of these options and then define them as mirrors down below in the mirror servus and you would use mirror in your config environments production file as your service so what I have set up here is one for digital ocean where we can use digital ocean spaces I have my bucket in NYC 3 and we can define in our credentials that yeah Milan encrypted file the keys for that so you can run rails credentials edit which I will link to in the notes below because if you haven't seen that episode the new credentials file replaces your secrets tat yeah Mille you could use your secrets that EML if you're upgrading from an old application this is a nice way to encrypt your keys and still keep them inside of your git repo so we'll be using digitalocean in production but I'm going to be using the local disk for development and one option here that I want to point out is host is sometimes required in local because if you're ever running on a different port it isn't smart enough yet to notice that you're using a different port so sometimes if you're using say Foreman you would have to define your host here so that it links to local host 5,000 instead of local host 3,000 which is the default so keep that in mind you may or may not want to add the host option in here for that because for whatever reason it doesn't know and I feel like that's probably something that will get fixed in a future version but right now you might have to manually get that fixed otherwise we'll get 404 is in development so that's all you have to do to set up active storage and configure it and then you can go to your models and define your attachments so here I've got a post class which is just simply title and body and there's no other attachment fields on it and we can simply say has one say attached header image and we can also say like has many attached uploads or files or photos or whatever you might want to call them you can just have those added like so so we'll have maybe a blog post with uploads that we have and two up these in your controller you'll go to your post controller you will go down to your params section and for any of the has ones you'll just have a header image or whatever your name is just like any other attribute it's going to accept the uploaded file like so but with your uploads it actually is going to be an array and so in those with MIT has many you can just simply say uploads and that gets pointed to square brackets then we can go open up our form to add that to it so let's create one at the top for our header image I'll have header image and that will be a header image instead of a text field I'm going to file field of course and we can go down underneath and add our uploads and this one I want to add the multiple is true option and that will tell our browser that we can select multiple files for that now I've got a post created already and we can go edit the header image by uploading you know some sorted picture here and then we can go to uploads and we can maybe grab but let's just grab a PDF an image and an SVG and add those as attachments so we'll go ahead and upload those will see that our post was successfully updated and if we go to our logs scroll down at the bottom we'll see that this was uploaded we get a patch and our uploads actually are doing some interesting things so it's deleting the existing attachments from there and then it's going to dis storage and uploading files we'll see it create active storage blobs with the metadata of image JPEG and all that good stuff then it goes down and updates our post after it's created our attachments that are the join records between the two so it's creating all of these associations for us and our attachments you can see the record type is for post uploads record ID so it's doing a polymorphic Association here and it's saying well this is for the uploads attachment type within the name field and then the Association is for the record field it's kind of cool how that works you can see that it is running all of that when we do our update and then at the very end it's in queued several analyzed jobs for each one of those files that we did so it's doing some analysis on those automatically integrating with active storage by the way and so you're going to want to run sidekick if you're using that to do some of this in the background you can also just leave that alone and it will run in your regular rails process immediately as it gets it so this is all nicely integrated with active with rails so you can see that it's using active job and all of that but we need a way to display these images now one cool thing about this is if you go to the post show page all you have to do to display an image is say at post dot header image an image tag for at post at header image you don't have to do the dot URL or thumb like some of the file uploading tools do you actually just say image tag and you pass in the image object and you're good to go so this will display the image it's kind of huge right now so maybe it'd be nice to resize it you can go to your gem file and add the mini magic gem to your gem file and that will allow you to resize images so now if we go back to post show after you've installed mini magic and you've installed image magic on your laptop or your server that will be required mini magic uses image magic as a separate command to resize images so keep that in mind then we can say a variant and we want to maybe resize this to 400 by 400 and display that in the browser so now we get a 400 by 400 image you can use image magics options to do other type cropping or maybe you wanted to resize to fit resize to fill whatever you want you can use all of those options from mini magic inside this variant method and so the variant method only applies to images though and that's something that we all notice if we were to go down here and create a div for all of those other uploads so our post has uploads and if we were to loop through each of these uploads and do the same thing with the image tag we're going to get an error here because we've uploaded a few things that are not actually images so we get an invariable error on this upload and if we look at the upload itself you can see that we don't really know which one it is but if you say upload dot blob you'll be able to figure out that this is our PDF that we uploaded and it is not resizable because it's not an image and you can't resize a PDF but there is built-in functionality for pre viewers which is really cool so here is what we can do let say upload that variable this is going to say well is our upload variable like can we resize it with mini magic and if that's true we can do that or we can also ask if the upload is pre viewable and in this case we can do preview instead of variant and resize that and so what this is going to do is create a preview image of our PDF it will use a thing called mu tools or mutual if you want to install that you can go to your terminal and run brew install mu PDF - tools and also ffmpeg if you want to create previews of videos you can use that tool to extract the thumbnail from a video and resize that as your preview so you can install these two tools on your machine and then as long as they're available you'll be able to you use them to resize and preview things so if we do this we will now get our cron PDF example right here and it's displayed it's cropped to maximum of 400 by 400 and you know it's a little narrower since we're not using you know resize to fill or anything like that and mini magic but it does work and you can click on these or well we can create these and make them clickable so we can have links to these images as well we can do the image like so and then we can link to upload here and if we do that we will be able to click on this image and then open it up and you'll see the route for this is slash rails active storage disk and then our big key for this file and you get a little bit of information about it at the end so this is pretty cool and you can also change things like the disposition so right now it's inline which is going to display it in the browser but you can change that disposition to I believe attachment which will cause your browser to download it instead of displaying it so when we link our PDFs here you might want to force that PDF is downloaded instead but we're now going to use instead of just upload directly we're going to use a new helper that you can use rails blog path this URL helper is going to point to the active storage blob you give it a blob and then you can say disposition attachment and then that URL and then that URL now will download the PDF directly instead so that's kind of nice for any of those where you may want to force it to be downloaded you can do that you don't have to do that with PDFs that's just a good example of how that might work now otherwise we also want to handle any cases where it's not variable and it's not pre viewable and we just want to that so maybe in this case that's one of the ones we want to use the rails blob path and we just went to link simply to the upload itself and so this case we might have our upload dot file name and we just want to link our go rails the SVG file here because it turns out that SVG s are not variable and they're not pre viewable and so that makes them kind of a weird case here because technically you can resize them but you can't resize them with mini magic because they're vectors they can be scaled automatically and they don't need to be resized with a tool like mini magic and so they kind of fit in this weird case but active storage still has another helper for us you can actually check if image is or an upload is an image and then in that case we know that it's not variable so we can have an image tag for the upload and maybe in this case we set the image tags width in HTML to 400 instead of setting that and so we could do that and go back to our browser now we'll see the SVG is displayed here appropriately but it's a little bit different than you might have expected because SVG s are kind of an odd type of image but we got the width of 400 and we'll still match that and everything will still work as you might expect it so you really will have to keep in mind how you want to display and render those uploads but that is up to you you have quite a bit of flexibility with that and I believe there are also some more helper methods like this to figure out what types those uploads might be so you can add your own views for each one of those options that works really well and does quite a good job of all of that now one last thing I would mention here is that with the previews you have just PDF and video formats right now we might do a future episode building a pre viewer for something like I don't know a slideshow like you could maybe take and upload a keynote slide deck and then maybe we'll pull out the first slide as an image if you're interested in that let me know in the comments below I'm sure someone's going to be working on adding more of those file types in there to be really cool to see as we go forward and last but not least is you want to be able to delete these images and one of the things with that is that you have a method so if we grab this post you have a method on your Association so a header image can call purge or purge later purge laters generally the better option to go and that will create a background job to run and delete it later but if you need it to run immediately you can just call purge and that will delete that file now same thing goes with the uploads if you wanted to delete all of them you can call purge on them and then it will delete all of them or you could say like your first upload and purge that one and so if we do that we can go back to our browser and you'll see our pron PDF is gone and that just deleted a single one but if we did uploads dot purge you can see it will delete all of them and all of our files are gone so keep that in mind that is how you delete your files from active storage you can basically pass in the active storage blob ID so when we're in the browser and you're doing one of these uploads you can actually print out the upload so for example post header image ID 18 that would be the thing we could go purge we can then look up active storage attachment dot find 18 should give us the exact same one back the header image and you could call purge on that to delete it so if you ever want to go and delete individual ones in the UI you could actually just submit over the IDS for the active storage objects and look them up through active storage and have them deleted like so instead of going through your model that will work pretty well as far as I know some of the other gems offered the ability for you to flag attachments is delete and so the you could submit your post and then it would delete those attachments but as far as I understand active storage doesn't have that ability right now maybe it'll be something added as a future feature but for now it's easy enough for you to create a new controller for attachments or uploads then look up the active storage attachment by ID and then call purge on it if you want to individually delete items that's not very hard now the last thing that I want to mention is that we will be talking about direct file uploads in a future episode that one's kind of more focused on JavaScript side of things and we can even integrate that with something like your WYSIWYG like you might use with tricks or something as well so the direct file uploads are pretty straightforward but we'll take a look at that in a future episode and if you have any questions let me know in the comments below or take a look at the edge guide on rails or the official guide whenever rails 5.2 gets released hopefully in the next couple of weeks and I will see you guys in the next episode peace [Music]
Info
Channel: GoRails
Views: 19,555
Rating: undefined out of 5
Keywords: Ruby, Ruby on Rails, Rails, Javascript, HTML, CSS, Servers, Databases, activestorage, rails 5.2, rails 5.2 active storage, active storage, active storage rails
Id: jtKEP_lsLco
Channel Id: undefined
Length: 20min 55sec (1255 seconds)
Published: Mon Mar 05 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.