Horses on Rails - Part 3 - ActiveAdmin and ActiveStorage

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay so the goal of today's lecture is to recreate some of what we've seen scaffolding do in the past which is give us the ability to have sort of web based crud for a model or models but to take that crud and put it behind a administrative login so that you could have administrative users that had full pride access to some data and the regular users if they didn't have the admin passwords wouldn't be able to do the crud so it's it's I think an improvement over what scaffolding offers because scaffolding offers use some views that you could layer your own authentication over top of but here we've built up a website that already has a few models already has some views and with very little coding we're gonna be able to add a whole admin dashboard for editing it so this is really nice for websites that are effectively just content management systems right so that's something where you your the site is primarily read-only from a user's perspective but from administrative perspective you want to be able to give one or more people the ability to add or edit or remove content and so there's a number of these kind of administrative frameworks available for rails the one that I've worked with for quite some time now is is active it men I'm also going to show you the Ruby toolbox the Ruby toolbox is a website that categorizes gems in the Ruby community and gives them a rating so that you can sort of know if you could feel confident about adopting this gem into your source code like anytime you are bringing in a third-party dependency into your code you have to spend a little bit time thinking about if this is something you really want to do because you're taking on all that source code that may not be maintained anymore right a lot of open source projects are maintained initially and then you know once things get difficult once the project becomes really popular and there's thousands of issues outstanding and sometimes just one programmer behind the whole thing but you get burnout happening and that project might get abandoned and so you don't ever really want to bring in an abandon project into your project unless perhaps you're in a situation where it does exactly what you want it's a work situation and you're willing to take on that project as something that you will then maintain as part of your day to day job for things like security patches and whatnot so there's some of those could be some trade offs where enough work has been done so that you don't have to do a certain amount of development on a thing but then it's going to be up to you to sort of manage and maintain this thing once it gets adopted into your project so here I've pulled up the rails admin interfaces section for ruby toolbox you can see there's a few here active admin as the highest rating and the rating is determined through a few different things the the system looks at popularity both by way of downloads of ruby gems and the number of stars it has on github how many Forks it has or how many Watchers it also looks at like when the project was initially released and when it was last active how often pull requests are actually getting accepted so is there like is this an open source project where there's a number of open source contributors that are creating pull requests and actually having those being merged in to the project are issues that are being raised in github actually being closed and sort of like reverse dependencies so what are the dependencies of this thing and it also gives it a little badge so this is a fairly high rating it's it's nine point four eight a long live project that still relief receives updates that's a pretty I would feel confident and I still do feel confident when I build rails websites I use active admit if you look at some of these others here's another one rails demand it's another long live project that still receives updates slightly a smaller score or lower score and that might have to do with maybe the the poll acceptance rates are you know when the last release was and then things quickly drop from there like this one there's a warning that there's a lot of openings so this one might still be under development like it looks like it last got a push back in September but it has a large number of open issues which is sort of a warning silence probably not getting the kind of love that it needs from whoever is maintaining it and then things go down from there these kind of admin builders exist across a lot of different framework so if you were working in the laravel world there's a bunch there including some by this or the chlorophyll team if you were working in the Python world the MBC sort of twice in that world is Django and all django applications come with a min back-end just by default that's just sort of what comes with a django app so that's part of the we need to pull in activity it's ok we've done our due diligence we've looked and we said ok we're happy that this can go into our project my next step is I would go and I would look it up on github and I would probably read through the readme and sort of see like how hard is this thing to bring into a project what are the dependencies that I'm bringing in along for the ride because with open-source everything is built on something else right so activate minutes elf is built on Barbara and devise and form tastic and inherited resources kaminari and ransack so there's a bunch of other gems that you're now bringing into your project and again if I was working I can doing this for a business or if I you know I was an employee I would probably go and look up all of these gems as well and maybe even their sub dependencies to see if they had a decent rating on the Ruby logs if they were actively being maintained or whatnot because it really can be problematic especially these days open source projects are starting to become attack vectors for hackers so if a hacker gains commits access to a very popular open source project they can inject like nefarious code into that project and have that code brought in to all of the projects that are using that gem or you know that have that gem as a dependency of a dependency of a dependency and this actually happens fairly regularly both in the Ruby community and in the JavaScript community and it usually happens because open-source is based on trust right you have sort of a set of core team members that are developing and working on the project and sometimes a core team member may be posing as a good actor may actually be a bad actor and how would you know and then they just sort of you know when no one's looking which often happens when a project starts to sort of fall under disrepair they'll slip in some malicious code into that gemin and see how many sites they can attack in that way so some warnings before you you go ahead and bring something like this into a project how do we do this okay so there's good documentation as well that's also something that I always look at no need to bring a gem into a project if there's no Doc's right here the docs are fairly good and we're just gonna follow them step by step to bring this into our project the I'll leave my server running and I'll go into a second terminal here and I also need to open up my gem file in the past we brought in some gems that have been like development gems so like faker and we scoped it to development this is a gem that we want in all rails modes and so I'm gonna put it here on line 33 so it's not wrapped in a group and I'm just gonna say gem I think it's active admit all one word it is and then I also have to say this gem devise so this is the active in minja mitts elf devise is an authentication gem that active admin depends upon it's sort of quote unquote optional for the project but I've never used active admin without it because it would mean that there would be no usernames and passwords and that's usually why I'm bringing active admit into my website is to bring in administrative usernames and passwords so I need both of those things in my gem file and then I can run a bundle install to actually bring those gems into the project and once that is in the project ruby gems can add generators to rails so we've done rails G for a bunch of things we now have a new generator that is from active admin which is the active underscore admin install generator as the active underscore at men install naming conventions aren't super standardized on active it men so you'll see sometimes it's active admin all one word and sometimes it's active underscore that meant this is one of the cases where we need the underscore running this sets up a few things creates a few files throughout our application we get a whole new folder in our app folder we get a app admin folder that we're gonna be working with today and we also get a few migrations to create the tables that active admin wants it wants one table for administrative users and a once a another table for comments and so this is these are gonna be comments that can be associated with any model or any row of any model in your system and they're only for the back end there so it so perhaps admins could have like a little comment thread around a particular row in a database table and so I can run rails DB migrate and bring those into the the project it'll generate those tables for us and now I can do it get ad and get commit it has also added a line to my seed script and so if I open up that seed script why you not open strange just my standard seat script it has added a line at the very bottom which is an admin user create statement for a default username and a very insecure password of password with a trailing modifier saying only do this in development mode right so that if you ran the seed script in production mode it would not add this user and so that's because it's a it's sort of a known email address with a variant secure password so it's just a little bit of caution around that so I can either run my seat script again or I could take this line here and just go into a rails console and run it and now if I ask if how many admin users there are there's one active it men is what is called a rails engine so the gem itself is like a mini version of a rails project that gets included within your rails project so this is one of the few times where you actually have to restart your server if it's already running and so I'm going to control see my server and I'm in a dead run rails s again I should be able to go back to my application it's gonna look a little weird and we're gonna fix that in a moment it's gonna look a little weird because active admin adds in some style sheets and some JavaScript that pollutes the application as a whole and we're gonna have to sort of shuffle it off to its own little place but for now I'll leave that as you can see my my stylings got a little strange but I should be able to go to slash admin and I should now be able to log in with that admin at example.com user with a password of password and get to this admin dashboard and it gives me some details it says like look at this app admin dashboard our B file if you want to customize this page I can look at the administrative users that are in the system and I could add a new user or edit existing users yes it did and so if we look at the routing if we go to our and a fig route something's wrong with my visual studio and now I can't double-click to open things strangely enough but yes it has added routes for us two kinds of routes devise routes which are for the authentication and then a whole slew of activate minarets that it just runs by calling active admin routes and injects them there so it's it's added a bunch and we could actually see that if we went to Rails slash info we'll see that there's a whole bunch of new active it mint and device related routes that have been added to the system yeah and if I go back over here you'll see that there's just comments table and this gives me the ability if I view a particular row in any table I can add a comment to it this user is a it's a nice little admin comment behind the scenes that's interesting in that the comments table is doing something which we don't discuss formally in this course is that it's a polymorphic table it's a table that can have an association with any table rather than a specific table which is a really really powerful feature of rails so before we've had associations that are direct foreign key associations to a specific table with polymorphic tables what's stored in each row is not only a foreign key but the table that it relates to so in that way you can have comments on any other table in the system and still maintain a foreign key relationship to those comments so it's a very powerful feature of the rails framework it's these polymorphic associations and comments does a good job of demonstrating that right now though we don't have our other things and the other things in our system here is we have a horse model and a breed model and so we have to register those with active admin and that's simple there's another generator for that its rails generate active underscore admin : resource and then the model name and so I would say in my other thing here rails generate active underscore admin : resource and I want that for a horse model and I want that for a read as well and you can see for each one of those it's creating a file in that app admin folder that was created for us can open those up as well and all it's doing is an active administer on the model and we're gonna fill in some blanks we've got that in both locations active hitmen register breed active administer horse I go back to my admin dashboard I suddenly have a horses and a breeds section it lists them alphabetically there's all my breeds I could create a new breed it knows about my validations this is an error that I'm gonna address in a moment but it'll know about my validations it's got a little asterisks here telling me that this is a required field it knows about all of my horses it gives me the ability to view them and delete them and edit them and create new ones filter very powerful sort of filtering capability you could filter based on an association you could filter based on columns when the date was created and updated all that kind of fun stuff that you might do as an administrator and you didn't have to write any code for that but we saw when I actually tried to go in and like create a new breed or even edit a new breed we got an error and the air is forbidden attributes error and what this is is that we just need to inside of these files whitelist the properties of this particular model that we want to be permitted to be changed and what the tool has done for us active admin is it's actually written the line for us and left it commented out and we can just uncomment it so active admin when it got installed actually when it introspect at our database and saw that a horse has a name and a breed in an age where I made it just looked at the schema file a number of legs at a top speed and it's assumed that I wanted to permit all those things so I just have to uncomment that line in each of these files that permit params line I'll save that one there I'll head over to the breed and a breed only has a name you don't need to do a permit params on the ID you just the anon key properties and once I've done that once I've permitted those parameters then I should be able to create a new breed of horse a gluttonous horse and it created it and if I edit that and I was to like leave off the name I can now see that the validations are actually working the name can't be blank I should be also able to like edit existing horses so there's a horse named Walter glutton and I can make that horse belong to this new breed and update it and if I tried to create a whole new horse we would see again the the various things being triggered in terms of validations you can also see that it knew about the Association and it fetched from the associated table all the possible breeds and it made that drop-down for me as well so it's just a lot happening here that we didn't have to code which is great the very first time I saw this gem I discovered it because students and the class discovered it and they were giggling at the back of the classroom because they thought they were getting away with with something because there was at the time quite a bit of marks associated for building an administrative dashboard for the website in the project and they were like a little bit apprehensive as to like were they gonna get those marks because they didn't code anything I was like yeah you're done and they're like oh because at that time I think I don't know there was a lot of marks for the administrative dashboard because before active admitted yeah we had to build this ourself and then ever since they discovered it I've just been using active admit in my own work great so um so yeah that's really all there is to bringing activit men into the system we brought it in as a gem we ran the installer we registered the the various columns there's a few things you gotta watch out for if you add new properties to a model you gotta go update those those files in the app admin folder right so new properties need to be added to this this whitelist beyond that now you have an administrative dashboard your system already now has device included and devises the gem that most rails programmers use for authentication so if you want to further add a authentication to your application for something other than admin users maybe you have regular users you could create another devise table and use devise and devise works in a similar way in that it provides a bunch of pre-generated views for things like end controllers for things like sign up and log in and forgot password and all those kind of standard authentication things that you need for an authentication system so any final thoughts or questions on this bringing active admin in to a project so there's one final thing that I need to do which is to fix up the the fact that the styling as sort of polluted the rest of the application and that's one of the places where if anything because active administered of a little long in the tooth in terms of its styling there are a few gems out there that sort of purport to be able to like change and sort of improve the styling of active it men I had a few students last term get those working and they had sort of nice sort of like materialized looking you know dashboards but I tried it and I wasn't able to get those gems going and I didn't want to battle them so yeah so take that for what it is there are some gems out there that will restyle it but they don't work easily or at least that wasn't my experience so how do i how do I make it so that active admins Styles don't leak into the rest of the application well let's first go see why they're doing that they're doing that because active it meant and it put its stylesheet right into the app asset style sheets folder that folder everything that's in there gets automatically loaded up by your rails application and it also put in this Java scripts folder a JavaScript file and that all the JavaScript in this this folder also gets automatically loaded so we don't want that and I'm not sure why active admin the gem doesn't just do what I'm about to do because there is actually a place for styling and JavaScript that belongs to a third-party different dependency and it's the vendor folder and so what we have to do is we have to manually vendor these assets and so there is this vendor folder here at the root of our project and inside of that vendor folder I have to make a new folder called assets and inside of it I have to make a new folder called Java scripts plural and style sheets plural and then I just need to move some files around so I'm gonna go into that assets folder and I'm gonna cut and paste the active admin stylesheet into my vendor assets style sheets folder and then I'm gonna go and grab the asset Java scripts active admin fee oh and I'm gonna put that into the vendor folder as well and then I need to restart my server and it should be should be fixed so I gotta go back over here control C and then rerun rails s and then the assets should be vendored and so if i go back to the application and reload it this goes back to my Bulma styling but if i go to the admin dashboard it should still have its styling as well and it does so that was sort of a the final step there i do i get status here i can yeah under cool okay that's part one of today's lecture the other thing that i wanted to show was images that's a very common thing that you would want to do with especially a content management type system like this one is to be able to attach images to particular database entries so for example a picture or at least an optional picture for each one of my forces and there over the years have been sort of a multitude of ways of doing this one of them is just to add a image URL column to manually put images into your app assets images folder and then just reference them by URL and so that that is doable but it has limitations right you got to do that manual work of bring files and putting them into that folder users can't just upload images along with creating a new horse you don't get any sort of automatic resizing or scaling or creating different versions of the images so that's sort of the baseline very simple way of adding images but it's not very flexible and past iterations of this course we used to use some gems one of the gems we used was paperclip use that for a while it's brought out by thoughtbot which is the same company that are the same consultancy that makes a lot of different ruby gems this one is now deprecated deprecated in favor of active storage which is now this or the core Rails way of adding files of any type to to a model in the past we also use something called carrier wave this is another gem for adding files that I imagine this one will probably end up getting deprecated as well because we do have active storage and so what sometimes happens with rails is there is this application called Basecamp and this is where rails began its life so David Hannah Mayer Hanson works for Basecamp and he created rails to help him build the very first version of Basecamp and so Basecamp is a rails application and new features of rails often start their life as pieces of Basecamp and once they get proven inside of the Basecamp project they get extracted out into separate gems and then brought into rails core and so a lot of the newer things that have been added to rails over the years have come from base camp and active storage is one of those so it's a way of attaching one or many files to a record and not only does it allow this to be done in a way where those files are being saved to disk but it also allows you to save those files to a cloud service allowing file uploads on a very small low usage site is fine if you want to use your disk but if you want to build a really popular website that is going to scale to a lot of different users or a lot of different images there's a chance you could fill up the hard drive that your server is running if you're just writing directly to disk or there's a chance that what you're deploying to has what's called an immutable file system like a file system that you literally cannot write to so later on in this course we deploy to Heroku and Heroku works on an immutable filesystem model in that you can use git to push your source code up to Heroku but at that point you cannot write permanently to the filesystem anymore you can write temporarily to the filesystem but anything you write will be blown away the next time you push and you deploy including any images you might have so it would be nicer to save to something like amazon's cloud service s3 or azor or Google Cloud storage and active storage supports all of those things as well so it's it's a really nice little system and I used it for the first time last term just when I was building it up a project myself and so we're just gonna walk through what it looks like to to add images to our horse model here and we'll just walk through the main rails guide and so the very first thing we need to do which is similar to active admin is to run a generator to get some database migrations in place for the various tables that active storage needs for saving data related to these images so even though it might save the images off on a cloud service or on to disk it still needs to save some metadata about these images into the database so step one here from the command prompt is to run didn't taste it hi there is Rails active underscore storage : install new migration has appeared in my DB migrate folder take a quick peek at what it is going to do and it's gonna create two new tables for me something called active storage blobs and something called active storage attachments and this is why I mentioned polymorphic references earlier in association with those comments is that an active storage attachment is also polymorphic in that you can have attachments that are associated with any of your models in your system without actually needing to put a foreign key on to those particular models the foreign key can be stored in this attachments table and maintained as a polymorphic reference and so I need to run these migrations so a rails DB migrate will let me do that that looks good it created the two different tables for me I can head back to the guide and it gives me a few little bits of information one it says the in the config folder there is a storage config file called storage dot yml and so maybe it's a good idea to go peek at that so in my config folder there should be a storage yml and so it looks like it's set up for in test mode the service for saving these files should be local disk and it should be in the temp storage folder when we're just using local storage alone which we're gonna use in our development mode it's gonna be disk and stored to a file named storage or a folder named storage and then it gives examples on how you would set up for Amazon s3 and Google and a xuer I played around with using Google last term and I found that was really easy to do I just needed there was like a key file that Google Cloud Services gave me as a way of authenticating my application and then once I put that into this this file I was able to save uploaded images to the Google cloud instead of my disk but in this case I'm gonna stick with disk base service and then where this actually gets used this information is in a rails application in the config folder there's also in environments folder which is a way of configuring how rails operates in the three different environments that rails can run in test development in production so we're running in development and we'll see in here the active storage service is set to local and this key here is a reference to this key here so eventually if we wanted Amazon to be used we'd uncomment this put in our information and then we could change this to Amazon here and then we would suddenly be using Amazon for our storage so that's good no changes there necessary it talks about various dis services bla bla bla down below here how do we actually attach files to records Thank You Jeremy there is a little bit of markup that we can add and it's sort of like how we do associations has one attachment is the thing that we can do to give a single file attachment to a particular record I've also played around with the the multiple one where there is like a has many attached things as well we'll just do the single for now and so I'm going to go into my force model and I will just say has one attached image I don't need to add any new columns to that horses table all I need to do is add this annotation to my model has one attached image there is a slight problem it's not really a problem it's just something that we're gonna notice is that when we go over to here to create a new horse there's no file picker for this and by default active admin generates these forms based on what it thinks you need and it looks to the model and it's not active storage aware so it doesn't automatically you could see maybe a future version of active administration but right now it doesn't know that it needs anything more than the breed the name the age the number of legs on the top speed okay so now I have to make it aware of that so I got to go back to the horse's admin file so this is the file in that app admin folder I need to add a new permit permitted parameter even though it's not directly on my object it's going to be passed in by the form an image so I have to add that to this permitted parameters as part of the whitelist the other thing I have to do is I have to customize the form that is being created and active administer it by setting up a form block and the docs for active admitted in this in this way so I'm gonna go to the section for customizing the form it's not what I want or what I guess it is yeah this is what I want so to recreate what's already in there right now I just need this so it's a form do which gets passed a block parameter called F F dot semantic errors is gonna show errors that are validation errors F thought inputs does that sort of magical introspection and figures out all the things that need to be part of the form and then F actions is going to give me my submitted cancel buttons all of this is something that was not coded by the active administer form builder and so that's just another gem in the Ruby ecosystem called form tastic that lets you build up really simple gems or sorry really simple forms and so with this in place I should this should look the same so when I go to create a new horse that should be identical as to what it was before now I have the ability to add to it and so what do I want to add I want to add a new collection of inputs what I want to be in charge of what these inputs are for I need a F input for an image I'm guessing I think this was it EFT on image or sorry I've got input it's the image that I'm trying to set and it's a file that I want or a file picker that I want there it is I've got a little browser and this should appear for existing horses as well I should now be able to browse to a horse and update it and okay we still can't really see it yet anywhere but it looks like things successfully worked I can sort of poke around and see we know that files are being stored into this storage folder there are some things in here some of them are probably from past experimentation with the with the other section but if I like go into there we can see there's a file when was that created I was created on a super one that was created on the 30th this one here and I bet you if I copy and paste this and rename it to a dot Bing my horse I'm obsessed with this picture of this horse it comes up when you use Google for horse which is like this is not really like a normal-looking horse but Google thinks it is and so I think it is alright so there you go so that that worked but but how do I actually then display this horse either you know in the back end somehow it'd be nice maybe on the show page to have a little thumbnail of the horse or or maybe on this list to have like a little tiny thumbnail of the horse and it would also be nice on the front of the website when we display horses that we would see that this horse you know image is and so we go back to our active admin Docs and we see how do we actually link to files and it looks like there's just a new helper that we can have used inside of our views called URL 4 and then in our case it'll be like horse dot image and we could pass that to the image tag helper and so I'm gonna go back over to boma because I want to augment my card component a little bit such that my card component has an image on top of it which is going to be this part so adding a div with a class of card image as the first element within my card class div so I'm just gonna copy and paste that whole little chunk there and I'm going to visit my horse partial so that's my underscore or study HTML to your beef and I can paste that right in here I go back to my application looks like that worked but I only want that to show up if the object that I'm working with actually has an image right so like for these other horses that don't have images I don't want that to be displayed and so we can have a quick little if statement in here that says something like if of course an image is present then display this thing and so that if statement will ensure that only horses with attached images will display an image so these will all go away but if we go back to Wally glutton it has room for an image the image isn't yet being shown but that's because I have to replace this hard-coded image tag here with a call to image tag and the URL or the force image it's what I need oh look at that so there's my horse it did not so that's a very good question did it automatically rescale it no it is boma boma does like responsive scaling so it's just almost doing some scaling but it's only done as a matter of the CSS but active storage is actually capable if what you're dealing with is an image of doing resizing for you you need a you need to install a Linux tool to do that so you need to from the command line do a sudo install on image magic and so image and it's spelt funny yeah like that or yeah like this so image magic has been around for a long time it's a it's a CLI tool for editing and resizing images of all sorts of types so if you install image magic into your Windows Linux subsystem you can then use active storage to resize your images on upload and it can make a whole bunch of different sizes for you so you can say on upload make me thumbnail like a medium size and a large size and you can specify the Heights and widths that work for you or layout you can specify just the width and it'll scale the height appropriately in the right correct ratio it'll do it such that I think it does the transformation on the fly and then then caches it yeah that is something that you you'll need to look into there's instructions here though as well like there's a new image gem that you have to add I I did it last term it wasn't that bad and it allowed for for image resizing as well yeah I wouldn't just because like if most images especially images from like cameras these days are going to be huge and so if we're doing the transformation client-side that we still have to deliver the entire payload to the user and they might be on like a mobile phone over like a you know a slow 3G and it'll just clog up the experience of the website so if possible you always want to do resizing on the server if you can and there's even image services so I had a few students last term that instead of doing it with active storage they were using like a cloud service for images that handled all the resizing as well and I think there was a gem for that I can't remember which clouds but there was a there was a pretty neat one though there was handling images for them so there are some marks available on the project for adding image uploads and also for dealing with the the resizing nature so for figuring out that whole process of installing image magic and then in terms of active storage going through and installing the image processing gem and then when you go to load up the image instead of just saying URL for you go to like user avatar in our case of the horse image and then you request a variant and then you specify some of the the resizing that you want to see it looks like I maybe don't even need URL for when I'm using it with Tagg see if this works yeah that's nice and so yeah this would be like you would add a variant for and then variant pose in Burien you just had a variant and then you would specify sort of what kind of resizing you would want right there on the fly and we could do the same kind of thing behind the scenes like if we wanted to customize active admin and so for example behind the scenes here if we wanted to customize this view here to display like a little thumbnail for the images just like we were able to override how active admin displays a form you can also override how active admin displays that index and so active in custom index I want index as a table yeah so here I could do selectable column a column and then my horse has like a name and here I would have to sort of like replicate these various things so I won't bother with all of them but you would have to go and replicate all of these but then I can also put in a column for the image and get it to use the act the act of storage image and resize it down to a small version there as well but I won't I won't implement that right now but that's another thing we could do to customize the back end I'm gonna just save these changes here to get and there we go that's what I wanted to demonstrate today are there any final questions about anything really that I've gone over today in terms of active admin or active storage in a rails application phyton well we can just leave this image up here for one more moment yes and then I will end the video
Info
Channel: Kyle Geske
Views: 1,308
Rating: undefined out of 5
Keywords: Rails, Ruby, Ruby on Rails, RubyOnRails, ActiveAdmin, ActiveStorage
Id: aRbQJacmXoU
Channel Id: undefined
Length: 53min 51sec (3231 seconds)
Published: Thu Oct 31 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.