<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andy Kelso on Medium]]></title>
        <description><![CDATA[Stories by Andy Kelso on Medium]]></description>
        <link>https://medium.com/@kelsocode?source=rss-4a8de24c85bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TRzIT9qh09Rl6CTIUTG0-A.jpeg</url>
            <title>Stories by Andy Kelso on Medium</title>
            <link>https://medium.com/@kelsocode?source=rss-4a8de24c85bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:26:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kelsocode/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rails Validations]]></title>
            <link>https://kelsocode.medium.com/rails-validations-3b01637ca2fa?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b01637ca2fa</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 18:27:19 GMT</pubDate>
            <atom:updated>2021-07-30T18:27:19.866Z</atom:updated>
            <content:encoded><![CDATA[<p>After spending a lot of time diving deeper into a couple other languages and frameworks, I recently returned to Ruby on Rails to build a new project. And after a little time away, I was once again blown away by the ease and ‘magic’ of Rails. It truly is a beast of a framework: incredibly intuitive, well thought-out, and full of developer friendly features and helpers.</p><p>While there are many features that deserve attention, I was particularly impressed with the implementation of Active Record Validations.</p><p>Active Record Validations are built to ensure that only good data is saved to the database. They are an effective way to do things like ensure that 2 users don’t wind up with the same user name or that the password that a user creates doesn’t contain a typo. And while there are other ways to ensure that invalid data doesn’t get saved to the database, Active Record Validations are usually the safest bet and are recommended by the Rails team in most scenarios.</p><p>Validations get triggered by several different methods and perhaps one of the most important times you want to check for valid data is when you are creating a new row in your database-such as a new User. In this case, validation checks get triggered when using the .save and/or .create methods.</p><p>For example, if you wanted to create a new User at signup and ensure that their email address was not being used by another user, you would first add this code to your User Model:</p><pre>class User &lt; ApplicationRecord<br>   validates :email, uniqueness: true<br>end</pre><p>Now, when you try to .save the record to the database, your validation will get triggered, and before an SQL INSERT operation is executed, Active Record will check to make sure that no other User exists who has that same email address! If the email exists, an error will be added to the ruby object’s errors collection and will be associated with it for future use (such as displaying the error to the user when validation fails).</p><p>Another great validation is :confirmation. This validation is perfect for making sure that the User typed in their email or password correctly. According to the docs, this validation will create a virtual attribute associated with the real attribute with _confirmation appended to the field’s name (ie. email_confirmation.</p><p>To implement as password confirmation, you might add this to your model:</p><pre>class User<br>   validates :password, confirmation: true<br>   validates :password_confirmation, presence: true<br>end</pre><p>The first line creates the virtual _confirmation attribute and will check to ensure that the :password and :password_confirmation fields match. (<em>note: your confirmation field on your form must have the </em><em>_confirmation virtual attribute as its ID. In this case: </em><em>:password_confirmation</em>). However, the validation will <em>only</em> get triggered if the password_confirmation value is NOT nil. Therefore, for extra bad-data protection, the second line:</p><p>validates :password_confirmation, presence: true</p><p>exists so that a user doesn’t skip the password confirmation field and submit the form-even if their password contains an unintended keystroke.</p><p>These are only 2 simple examples of the amazing Validation helpers included with Active Record in Rails. There are many other validations and many ways to use them, combine them, and/or skip them altogether. They are so useful and easy to implement that I had never given them a second thought. But it’s great to step back, examine how they work, and fully appreciate what a beneficial and efficient tool they are for developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b01637ca2fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple User Types]]></title>
            <link>https://kelsocode.medium.com/multiple-user-types-3ca775a32fc0?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca775a32fc0</guid>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 14:13:07 GMT</pubDate>
            <atom:updated>2021-07-23T14:13:07.078Z</atom:updated>
            <content:encoded><![CDATA[<p>It seems that most of the time, having only one user model gets the job done when building an app with standard authentication. A User signs up, signs in, can access information like most other Users, and signs out.</p><p>But how do you make it work on the rare occasion that your app has more than one type of user? There are several different approaches that you could take to handle this problem-including using gems dedicated to this exact situation. But I am going to show one way that I made it work on an app that I recently built.</p><p>My project is an Audition Tracker App which allows 3 different User models (Actors , Directors, CastingDirectors) to track and make Notes for their Auditions. I created the 3 separate user models because each User plays such a different role in the audition process. I wanted the Users to be <em>associated</em> with each other rather than all lumped into a single User model-only identified by a type: attribute. For example, actors should be able to view all the directors that they have auditioned for (ie: @actor.directors).</p><p>The first adjustment that I made to my session-based authentication was how to sign in a user on the server given that not all users will be within the same model. If I used the standard session[:user_id], my app wouldn’t be able to tell the difference between and Actor who’s id = 3 and a Director who’s id = 3.</p><p>Instead of session[:user_id], the key became session[:actor_id] or director_id or casting_director_id accordingly. This allowed me to easily track the user type, but also required some adjustments to other standard methods. For example, my current_user method went from one find_by method to this:</p><pre>def current_user<br>   <br>   if session[:actor_id]		<br>       @current_user ||= Actor.find_by(id: session[:actor_id])<br>   elsif session[:director_id]<br>       @current_user ||= Director.find_by(id: session[:director_id])<br>   elsif session[:casting_director_id]<br>       @current_user ||= CastingDirector.find_by(id: session[:casting_director_id])<br>					<br>end</pre><p>This is effective and allows the app to verify the user type by simply checking to see if their model_id exists within the session hash. For example, a user may not have access to a Casting Director’s contact information if session[actor_id] is present.</p><p>Another adjustment that I had to make was how to identify &amp; find the user based on their type at sign-in. The easiest way to do this was to create a select input that requires the user to choose their user-type at sign in. In my #create sessions method, I access this info via the params[:user_type] which then points to the appropriate model:</p><pre>@user = params[:user_type].constantize.find_by(email: params[:email])</pre><p>The key to making much of this ‘multiple user-types’ flow work is the constantize Rails method seen above. When used in this way, this method gets called on a string and returns a model with the same name-<em>if one exists</em>. If a model with the same name does NOT exist, it will throw an error. Therefore, it is imperative to make sure that the sign-in form sends the user-type attribute as a string, spelled in the <em>EXACT</em> format as the name of your model. For example &#39;Actor&#39;.constantize will correctly return my Actor model, but &#39;actor&#39;.constantize will error out.</p><p>My sessions#create method ended up looking like this:</p><pre>def create<br>   @user = params[:user_type].constantize.find_by(email: params[:email])<br>   <br>   if @user &amp;&amp; @user.authenticate(params[:password])<br>      session[&quot;#{params[:user_type].downcase}_id&quot;.to_sym] = @user.id<br>      redirect_to profile<br>   else<br>      flash[:error] = &quot;Invalid email address or password&quot;<br>      redirect_to new_session_path<br>   end<br>end</pre><p>While there are several different approaches available to take in order to handle multiple user models, I found this one to be fairly straightforward and accomplished my goals for this particular app without making the process overly complicated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca775a32fc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hover to Affect Sibling Elements]]></title>
            <link>https://kelsocode.medium.com/hover-to-affect-sibling-elements-87cd85549814?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cd85549814</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[hover]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 19:11:08 GMT</pubDate>
            <atom:updated>2021-07-16T19:11:08.229Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently wanted to implement a style feature on a project which, upon hovering over an element, would affect not only the element being hovered over, but it’s neighboring elements as well. For example, the element being hovered over would increase in size while its neighboring (sibling) elements would shrink:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*SyslEwCjPkpcUEbSn_o6kQ.gif" /></figure><p>The way I did this was to first, apply a default :hover style to all the affected elements via the child combinator selector (&gt;). This style should be what happens to the hovered element’s siblings (in the example mentioned above, this style would be to shrink:</p><pre>#parent:hover &gt; * {<br>   transform: scale(0.5);<br>}</pre><p>(if you put the :hover after the * instead of after the parent element, it will only affect the element that is being hovered over instead of <em>all</em> child elements when <em>any</em> of them are hovered over)</p><p>The next thing to do is create the emphasis style for the element that you are hovering over. In this case, we want to enlarge the element while all the others are shrinking. To do this, you simply add the :hover style to the specific element being hovered over:</p><pre>#parent:hover &gt; *:hover {<br>   transform: scale(1.5);<br>}</pre><p>Now, when you hover over your element, it will increase in size to1.5 while its sibling elements will decrease in size to 0.5!</p><p>If you stop there, you may notice that the child elements transform to their default :hover style whenever you mouse over the parent element-even if you are in the no-man’s-land gap between sibling elements. To fix this, we need to adjust the pointer-events properties of the parent and children which sets when an element can become the target (ie. determines if anything can happen when the element is moused over) of a pointer event.</p><p>Under the parent element you’ll set the value to :none:</p><pre>#parent {<br>   pointer-events: none;<br>}</pre><p>Leaving it this way makes it so that any hover events within the parent will be disabled/will not work. This allows us to ‘turn-off’ the gap between elements, but also disables our shiny new effect. To get it to work when hovering over our desired elements, we need to add:</p><pre>#parent &gt; * {<br>   pointer-events: auto;<br>}</pre><p>This selects only the parent’s children (not the gap in between them), and effectively ‘turns-on’ any hover effects and/or pointer-events!</p><p>All together, it would look like this:</p><pre>#parent {<br>   pointer-events: none;<br>}</pre><pre>#parent &gt; * {<br>   pointer-events: auto;<br>}</pre><pre>#parent:hover &gt; * {<br>   transform: scale(0.5);<br>}</pre><pre>#parent:hover &gt; *:hover {<br>   transform: scale(1.5);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cd85549814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstracting your form’s handleChange function(s) in React]]></title>
            <link>https://kelsocode.medium.com/abstracting-your-forms-handlechange-function-s-in-react-717a64e207a2?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/717a64e207a2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[controlled-component]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 18:55:30 GMT</pubDate>
            <atom:updated>2021-07-10T19:02:49.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating controlled components in React is an extremely helpful way to keep track of your user’s inputs and aids in passing the form data to wherever it needs to go. However, if you are working with a form that contains multiple inputs and are using a functional component, it can be tedious to have to create multiple pieces of state with useState &amp; handleEachInputsChange functions in order to save the data to state.</p><p>A DRYer way to do this is to utilize useState only once and compose the component’s state to mirror something closer to the way you might handle state in a class component.</p><p>For example, I was working on an app with a form which had 6 separate inputs. As I started to build my component, I initially started to structure my controlled form by creating state for each input:</p><pre>const [inputOne, setInputOne]  = useState(&quot;)<br>const [inputTwo, setInputTwo] = useState(&quot;)<br>const [inputThree, setInputThree] = useState(&quot;)<br>...etc...</pre><p>While this is already a bit repetitive, the thing that really made me start wondering if there was a DRYer way of doing things was when I had to start writing a different handleChange function for each input’s onChange event:</p><pre>const handleInputOneChange = (e) =&gt; setInputOne(e.target.value)<br>const handleInputTwoChange = (e) =&gt; setInputTwo(e.target.value)<br>const handleInputThreeChange = (e) =&gt; setInputThree(e.target.value)<br>...etc...</pre><pre>&lt;Form&gt;<br>   &lt;input type=&quot;text&quot; placeholder=&quot;First Input...&quot; onChange={handleInputOneChange} value={inputOne}/&gt;<br>   &lt;input type=&quot;text&quot; placeholder=&quot;Second Input...&quot; onChange={handleInputTwoChange} value={inputTwo}/&gt;<br>   &lt;input type=&quot;text&quot; placeholder=&quot;Third Input...&quot; onChange={handleInputThreeChange} value={inputThree}/&gt;<br>...etc...</pre><p>While this will get the job done, it creates a lot more work by repeating code with minor differences and increases room for error.</p><p>My solution was, instead of creating 6 separate state objects to represent each input individually, I declared only 1 state object which holds all the form data. This allowed me to abstract my handleChange function without declaring additional variables or writing separate handleChange functions for each input:</p><pre>const [formData, setFormData] = useState({<br>        inputOne: &quot;&quot;,<br>        inputTwo: &quot;&quot;,<br>        inputThree: &quot;&quot;,<br>        inputFour: &quot;&quot;,<br>        inputFive: &quot;&quot;,<br>        inputSix: &quot;&quot;<br>    })</pre><p>Now, I simply needed to write one handleChange function. This function ended up looking similar to a class component that utilizes setState and requires the use of the spread operator to make sure preexisting state data doesn’t get lost. I also needed to assign the name property to my inputs which corresponds to each input’s key in the state object in order to be able to assign it’s value in my now abstracted handleChange function:</p><pre>const handleChange = (e) =&gt; {<br>        setFormData((prevalue) =&gt; {<br>            return {<br>                ...prevalue,<br>                [e.target.name]: e.target.value<br>            }      <br>        })<br>    }</pre><pre>&lt;Form&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputOne&quot; placeholder=&quot;First Input...&quot; onChange={handleChange} value={formData.inputOne}/&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputTwo&quot; placeholder=&quot;Second Input...&quot; onChange={handleChange} value={formData.inputTwo}/&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputThree&quot; placeholder=&quot;Third Input...&quot; onChange={handleChange} value={formData.inputThree}/&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputFour&quot; placeholder=&quot;Fourth Input...&quot; onChange={handleChange} value={formData.inputFour}/&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputFive&quot; placeholder=&quot;Fifth Input...&quot; onChange={handleChange} value={formData.inputFive}/&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;inputSix&quot; placeholder=&quot;Sixth Input...&quot; onChange={handleChange} value={formData.inputSix}/&gt;<br>&lt;/Form&gt;</pre><p>While this certainly is not necessary to do when building smaller forms with fewer inputs, it can be a helpful way of structuring a component with many inputs, and will deliver cleaner, less-repetitive results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717a64e207a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redirect After Multiple Uploads with React]]></title>
            <link>https://kelsocode.medium.com/redirect-after-multiple-uploads-with-react-50e413501438?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e413501438</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 19:01:53 GMT</pubDate>
            <atom:updated>2021-07-02T19:04:50.401Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a React project that I have been working on which allows a user to upload multiple files/photos all at once using a single form/dropzone. In order to improve efficiency, I have also implemented direct upload functionality from React to Amazon Web Services(AWS) S3 storage.</p><p>The upload process to AWS requires each file to be sent individually using its own pre-signed URL and individual fetch request (more details on that in a future post!). With each file being a different size and each fetch request finishing at different times, I found myself trying to figure out the best way to redirect my user to another section of my app after all the uploads were completed. If it was only 1 file with only 1 fetch, I could simply put the redirect in a .then() attached to the request. But I couldn’t do that with multiple uploads.</p><p>The way I ended up solving this problem was basically adding a counter to my Upload component’s state which keeps track of the number of uploaded files and compares that to the total number of files. I called this counter filesUploaded and set its initial value to null:</p><pre>const [filesUploaded, setFilesUploaded] = useState(null)</pre><p>In my handleSubmit , I increase the value of filesUploaded in the .then() method after each file gets successfully upload to S3:</p><pre>for(let i = 0; i &lt; files.length; i++){<br>    awsUpload(res.post_urls[i], files[i])<br>    .then(res =&gt; {<br>        if(res.ok){<br>            setFilesUploaded(++filesUploaded)<br>        }<br>    }<br>}</pre><p>files-state variable containing all the files to be uploaded; <br>awsUpload -fetch function which uploads to AWS; <br>post_urls -array of pre-signed urls for each file</p><p>Now that I had a way of keeping track of the upload progress, I was able to compare that progress to the total number of files which needed to be uploaded. When the 2 numbers matched, my component would know that it was ready to redirect to the next step in my user’s flow. I created a function called sendToGalleries() and placed it within a ternary statement in my return which will redirect my user once their uploads are completed:</p><pre>const sendToGalleries = () =&gt; {<br>    return &lt;Redirect to=&quot;/my-galleries&quot; /&gt;<br>}</pre><pre>return (<br>    &lt;div &gt;<br>        { files.length == filesUploaded ? sendToGalleries() : null }<br>        &lt;h3&gt;Upload a Gallery&lt;/h3&gt;<br>        etc...</pre><p><em>Note: I set my </em><em>filesUploaded initial state to </em><em>null rather than 0 so that when the component is initially mounted, comparing </em><em>files.length to </em><em>filesUploaded will not return a truthy result which would redirect before the user ever gets to see the Upload form.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e413501438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FormData to Upload Multiple Images]]></title>
            <link>https://kelsocode.medium.com/using-formdata-to-upload-multiple-images-73a6b1aaa179?source=rss-4a8de24c85bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/73a6b1aaa179</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Andy Kelso]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 14:38:53 GMT</pubDate>
            <atom:updated>2021-06-25T14:38:53.149Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I’ve been working on an app which allows a user to upload a gallery of photos and narrow down which photo(s) are their favorite from that gallery. I’ve been using a React frontend and a Rails API backend.</p><p>As I was building my react, Upload component, I needed to find a way to send the user’s images-all at once- to my Rails backend. At first, I tried to create an object which contained my array of images. ie:</p><pre>const gallery = { images: imagesFromInput }</pre><p>However, when I tried to attach the object to the body of my fetch request to POST the gallery to my rails backend, the data was lost.</p><p>After digging around, I discovered that I needed to use the FormData object with my fetch request. From the docs:</p><blockquote>The <strong>FormData</strong> interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send">XMLHttpRequest.send()</a> method. It uses the same format a form would use if the encoding type were set to &quot;multipart/form-data&quot;.</blockquote><p>First, I needed to create a FormData object:</p><pre>const galleryData = new FormData()</pre><p>In order to add a key/value pair to the object, you use the append method:</p><pre>FormData.append(&#39;key&#39;, &#39;value&#39;)</pre><p>At first, I tried to simply append my array to the FormData object like so:</p><pre>galleryData.append(&#39;images&#39;, imageArrayFromInput)</pre><p>However, the array structure was lost in translation and the files were unusable to my backend.</p><p>After poking around for hours, banging my head against the wall, and trying multiple attempts at getting the array to append to my FormData object, I finally discovered the proper way to append my image array to the object! In order for the FormData to send the value as a readable array without losing your data, you must simply add [] to the end of your key in the append method and loop through your array in order to push each image onto the array:</p><pre>FormData.append(&#39;key[]&#39;, array[0])<br>FormData.append(&#39;key[]&#39;, array[1])<br>etc...</pre><p>My final code for structuring my FormData object looks something like this where files is my state object which contains the user’s images from the form:</p><pre>const galleryData = new FormData()<br>for (let i = 0; i &lt; files.length; i++) {<br>   galleryData.append(&#39;images[]&#39;, file[i])<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a6b1aaa179" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>