<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: samanthamarberger</title>
    <description>The latest articles on DEV Community by samanthamarberger (@samanthamarberger).</description>
    <link>https://dev.to/samanthamarberger</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F928943%2Fb1c67ed7-8682-4663-9a55-cf414d732772.jpeg</url>
      <title>DEV Community: samanthamarberger</title>
      <link>https://dev.to/samanthamarberger</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/samanthamarberger"/>
    <language>en</language>
    <item>
      <title>Enhancing Event Management with FullCalendar in React Rails</title>
      <dc:creator>samanthamarberger</dc:creator>
      <pubDate>Thu, 16 Nov 2023 03:36:53 +0000</pubDate>
      <link>https://dev.to/samanthamarberger/enhancing-event-management-with-fullcalendar-in-react-rails-1233</link>
      <guid>https://dev.to/samanthamarberger/enhancing-event-management-with-fullcalendar-in-react-rails-1233</guid>
      <description>&lt;h2&gt;
  
  
  Struggling with event management in your React Rails app? Discover how FullCalendar can simplify the process!
&lt;/h2&gt;

&lt;p&gt;Event management can be such a hassle when creating applications that require scheduling. It is important for the users of your application to have visual representation of current appointments and future bookings. A user-friendly calendar component allows for easy user scheduling or editing for anything that involves a date and time. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://fullcalendar.io/docs#main"&gt;FullCalendar&lt;/a&gt; is a JavaScript library that can be used in your Rails/ React applications. It is a powerful and customizable solution for handling event management within our applications. &lt;/p&gt;

&lt;h2&gt;
  
  
  Basics of a React Rails Application
&lt;/h2&gt;

&lt;p&gt;React Rails applications are simple and powerful to use. Allowing you to have front and back-end functionality in the same place saves time and space. The simplicity through associations in Rails and the ease of React and components allow for an efficient development experience. &lt;/p&gt;

&lt;p&gt;React components are great for the separation of concerns, and you can pass variables and functions through the use of state and props between components. This keeps your code clean, organized, and easy to debug. &lt;/p&gt;

&lt;h2&gt;
  
  
  React Rails Application
&lt;/h2&gt;

&lt;p&gt;I am going to assume that you already have your React Rails application up and running with your models built and ready to go. Using a recent project of mine, I have an application where a trainer can post their availability and the clients can then book on those postings. I am going to show the Trainer side of posting/ editing/ deleting availabilities. My simplified models and migrations look like this:&lt;/p&gt;

&lt;p&gt;The Availability Model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Availability &amp;lt; ApplicationRecord
    belongs_to :trainer
end

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateAvailabilities &amp;lt; ActiveRecord::Migration[6.1]
  def change
    create_table :availabilities do |t|
      t.integer :trainer_id
      t.datetime :start
      t.datetime :end

      t.timestamps
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Trainer Model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Trainer &amp;lt; ApplicationRecord
    has_many :availabilities
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateTrainers &amp;lt; ActiveRecord::Migration[6.1]
  def change
    create_table :trainers do |t|
      t.string :name

      t.timestamps
    end
  end
end

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have these associations in place, we know that the relationship between Trainer and Availabilities is a one to many allowing for easy access within our application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installing and Configuring FullCalendar
&lt;/h2&gt;

&lt;p&gt;To install FullCalendar, type into your terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save @fullcalendar/react
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will also need 3 FullCalendar Plug-ins to make our Calendar more interactive. Type into the terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save @fullcalendar/daygrid @fullcalendar/timegrid @fullcalendar/interaction
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With everything installed, we need to import the plug-ins to our react parent components. Let's create a component called Calendar. It should look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';


function Calendar() {

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With our plug-ins imported and our component initialized, we can now add functionality. &lt;br&gt;
Let's start with rendering our Calendar on the page and allow the user to select between day, week, and month views, as well as the previous, next, and today buttons.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Calendar() {
    return (
        &amp;lt;div className="calendar"&amp;gt;
            &amp;lt;FullCalendar 
            initialView='dayGridMonth'
            headerToolbar={{
                left: "prev,next,today",
                center: "title",
                right: "dayGridMonth,timeGridWeek,timeGridDay"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            /&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have set the initial view to dayGridMonth so that when the Calendar is initially rendered, you are looking at a month calendar view; however, the default can be set to day or week. &lt;/p&gt;

&lt;p&gt;If you look at your calendar you should see something like this: &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w8rkU7qJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4y6yuabzu3085agtpg6u.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w8rkU7qJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4y6yuabzu3085agtpg6u.jpg" alt="Image description" width="800" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we have a simple and clean calendar that the user can toggle through, let's add some functionality!&lt;/p&gt;

&lt;p&gt;So that I can see the events I want to schedule, I have to add an events variable that will take in events as props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;events={events}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That simple bit of code will allow me to view the events passed in. Next let's add a callback prop that will allow me to click on the calendar and perform the callback function passed in.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;selectable={true}
eventClick={eventClick}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You want to set selectable to true if you have any interaction with the calendar, whether that be to schedule, edit, or even to get a pop-up view. We are not able to click an event, but what if we want to pass in a callback that will allow us to select a date?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dateClick={dateClick}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easy enough! Let's see what this looks like all together, don't forget to pass in the callback function props for Calendar to put to use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Calendar({ events, eventClick, dateClick }) {

    return (
        &amp;lt;div className="calendar"&amp;gt;
            &amp;lt;FullCalendar 
            initialView='dayGridMonth'
            headerToolbar={{
                left: "prev,next,today",
                center: "title",
                right: "dayGridMonth,timeGridWeek,timeGridDay"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            events={events}
            selectable={true}
            eventClick={eventClick}
            dateClick={dateClick}
            /&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great! We now have a calendar that the user can interact with. Let's put it to use. &lt;/p&gt;

&lt;p&gt;We want an Availabilities component where a trainer can interact with the calendar. First step, we make sure to import our Calendar into the Availabilities component. From here we can set our events that we will pass to the calendar.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const availabilities = user.availabilities.map(a =&amp;gt; ({
        title: `Availability`,
        start: a.start,
        end: a.end,
        availability_id: a.id,
    }))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These availabilities will be passed as the events and displayed on the calendar, I am using seed data for this. &lt;/p&gt;

&lt;p&gt;We now want to build a callback that we can send to Calendar to schedule appointments. I would create a form that the user can fill in start and end times, and on submission, send it to the back end create action in the availabilities controller. This is what that submission callback, addAvailability, will look like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    const [selectedDate, setSelectedDate] = useState([])
    const handleDateClick = (info) =&amp;gt; {
        setSelectedDate(info.dateStr)
    }
    const [start, setStart] = useState(`${selectedDate}T11:00`)
    const [end, setEnd] = useState(`${selectedDate}T12:00`)

    function handleSubmit(e) {
        e.preventDefault()
        addAvailability({
            start: start,
            end: end
        })
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have the times set to default but using a form, the user can change that. Now that I have events and a callback function I can return a calendar that visualizes the availabilities and allows for user interaction.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Calendar from "./Calendar";

function Availabilities() {
    const [selectedDate, setSelectedDate] = useState([])
    const handleDateClick = (info) =&amp;gt; {
        setSelectedDate(info.dateStr)
        setCreateModalOpen(true)
    }
    const [start, setStart] = useState(`${selectedDate}T11:00`)
    const [end, setEnd] = useState(`${selectedDate}T12:00`)

    function handleSubmit(e) {
        e.preventDefault()
        addAvailability({
            start: start,
            end: end
        })
    }

    const availabilities = user.availabilities.map(a =&amp;gt; ({
        title: `Availability`,
        start: a.start,
        end: a.end,
        availability_id: a.id,
    }))


        return (
            &amp;lt;div&amp;gt;
                &amp;lt;Calendar
                    events={availabilities}
                    dateClick={handleDateClick}
                /&amp;gt;
            &amp;lt;/div&amp;gt;
        )
    }
    else {
        return &amp;lt;h1&amp;gt;Error: Not Authorized&amp;lt;/h1&amp;gt;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember, I have a form that on submission creates and posts the new Availabilities, but with those additions, my Calendar now looks like this!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VIbPoL8h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jp86w8l7w3fh2lutmxoc.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VIbPoL8h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jp86w8l7w3fh2lutmxoc.jpg" alt="Image description" width="800" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How great is that! We now have a component that can be used for all different scenarios through the use of callback functions as props. &lt;/p&gt;

&lt;p&gt;This is a great tool because it allows you to continue using Rails in the way you already know how, but have a much easier and interactive user interface. There are so many ways you can customize your Calendars, be sure to check out &lt;a href="https://fullcalendar.io/docs#main"&gt;Full Calendar's official docs&lt;/a&gt; for more great ways to customize. &lt;/p&gt;

&lt;p&gt;In conclusion, incorporating FullCalendar into your Rails/React applications provides a powerful and customizable solution for managing events, appointments, and schedules. The seamless integration of React components with Rails associations offers an efficient development experience, allowing for the creation of user-friendly and interactive calendars.&lt;/p&gt;

&lt;p&gt;By following the step-by-step instructions for installing and configuring FullCalendar, we've demonstrated how to create a dynamic and responsive calendar component. Whether you're building a scheduling system, managing appointments, or handling event bookings, FullCalendar's flexibility allows for customization to suit various use cases.&lt;/p&gt;

&lt;p&gt;Incorporate these practices into your Rails React projects, and empower your users with an intuitive and engaging event management experience. Feel free to share your thoughts, experiences, and any challenges you encounter in the comments. Happy coding!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding Authorization vs. Authentication in Rails</title>
      <dc:creator>samanthamarberger</dc:creator>
      <pubDate>Thu, 05 Oct 2023 19:08:11 +0000</pubDate>
      <link>https://dev.to/samanthamarberger/understanding-authorization-vs-authentication-in-rails-cgi</link>
      <guid>https://dev.to/samanthamarberger/understanding-authorization-vs-authentication-in-rails-cgi</guid>
      <description>&lt;p&gt;We all know the importance of security in our web applications. We need to protect our data and customers from potential data theft or other types of cybercrime. However, there are different pieces required to make a secure application. Things like proper session management or the use of cookies can be useful, but today I am going to be writing about Authorization and Authentication. When I first learned about these I struggled remembering which was which and how to implement them. So for those struggling with that also, and for myself, this post is for you.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Authentication
&lt;/h2&gt;

&lt;p&gt;Authentication was explained to me this way, and it's a common way of explaining it because it sticks: &lt;br&gt;
Authentication is like going to the club and once your ID is checked, you receive a wristband or a stamp. After that, you can come and go from the club, or order drinks, without getting your ID checked because those working there can see you have the wristband proving that you are old enough. &lt;/p&gt;

&lt;p&gt;Authentication is how your application can verify that the user is who they say they are and is already allowed to be there. &lt;/p&gt;
&lt;h3&gt;
  
  
  Authentication in Rails
&lt;/h3&gt;

&lt;p&gt;Let's go through a simplified login process. &lt;/p&gt;

&lt;p&gt;1) The user will fill in a login form on the front end with, for simplicity purposes, just a username.&lt;/p&gt;

&lt;p&gt;2) On submit, a POST request will be sent to /login on the Rails backend&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;post "/login", to: "sessions#create"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) In a SessionsController we will set a cookie on the user's browser by using the ID of the user in the session hash&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SessionsController &amp;lt; ApplicationController
  def create
    user = User.find_by(username: params[:username])
    session[:user_id] = user.id
    render json: user
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With these steps in place, our user is logged in and the Rails backend has a way of identifying the user by setting the sessions hash:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;session[:user_id] = user.id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We would also need to make sure that the front end is saving the logged-in user's information which can be done using state. However, if there is a page refresh, the backend has the session information, but the state is lost, so we have to reach into the backend and get the user info to set state. Here is how: &lt;/p&gt;

&lt;p&gt;1) Make a route that will retrieve the user data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;get "/me", to: "users#show"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) Write a show controller action in the UsersController that will find the user using the session hash. (Remember to add error handling)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UsersController &amp;lt; ApplicationController
   def show
       user = User.find_by(id: session[:user_id])
       if user
           render json: user, status: :ok
       else
           render json: { error: "Not Authorized" }, status: :unauthorized
       end
   end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) On application load, set the user to the user information that has been fetched. (Remember to add error handling)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [user, setUser] = useState(null);

  useEffect(() =&amp;gt; {
       fetch('/me')
           .then(r =&amp;gt; r.json())
           .then((userData) =&amp;gt; {
               if (!userData.error) {
                   setUser(userData)
                   fetchTrails()
                   setLoggedIn(true)
               }
               else {
                   console.log(userData.error)
               }
           })
   },[])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our user now has their virtual wristband on and doesn't need to "re-ID" until they completely log out.&lt;/p&gt;

&lt;h4&gt;
  
  
  Speaking of Logging Out
&lt;/h4&gt;

&lt;p&gt;Logging out is simple, all that you need to do is...&lt;/p&gt;

&lt;p&gt;1) Add a delete route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;delete "/logout", to: "sessions#destroy"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) Add a destroy controller to the sessions controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def destroy
  session.delete :user_id
  head :no_content
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) And lastly perform the front-end functionality by setting the setUser back to null and any other log-out functionality you might have. &lt;/p&gt;

&lt;p&gt;This will then terminate the "wristband" that the user has and they will have to re-authenticate to get back into the application club.&lt;/p&gt;

&lt;h2&gt;
  
  
  Authorization
&lt;/h2&gt;

&lt;p&gt;To continue on the previous analogy, let's say this bar is 18+. You need to be 21 to drink, so at the entrance, you get two wristbands if you are above 21, one to be admitted in and the other for drinks. Meanwhile, 18-20-year-olds only get one wristband for admittance. &lt;/p&gt;

&lt;p&gt;Authorization is allowing certain users permission to access specific routes. This could be useful for applications with premium subscriptions, or applications used by managers and employees. Different types of users need different types of access. &lt;/p&gt;

&lt;h3&gt;
  
  
  Authorization in Rails
&lt;/h3&gt;

&lt;p&gt;To authorize, or not authorize, a user, you want to create a method that your controllers can refer to that says, "do not authorize unless there is a session id".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ApplicationController &amp;lt; ActionController::API
  before_action :authorize

  def authorize
    return render json: {error: "Not authorized"}, status: :unauthorized unless session.include? :user_id
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I like to put my authorization method in the ApplicationController so that all other controllers that inherit from it have access.&lt;/p&gt;

&lt;p&gt;You might be wondering what before_action is. It is a call to ActionController's class method before_action. It is a filter method that runs before any actions in that controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;before_action :authorize
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if I wanted a teaser for my application where anyone can look at it, but can't partake in any of the cool features, I could include something called skip_before_action on the index action. This allows those not logged in or those who don't have an account to see the index data but not have the ability to do anything with it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Controller &amp;lt; ApplicationController
  skip_before_action :authorize, only: [:index]

end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Back to our analogy, the before_action and skip_before_action are easy ways to allow those over the age of 21 to order drinks and those under the age to just be there and not order a drink without any need to explicitly check ID again. &lt;/p&gt;

&lt;h2&gt;
  
  
  Key differences between Authorization and Authentication
&lt;/h2&gt;

&lt;p&gt;After examining Authorization and Authentication, we can conclude some of their differences. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Authentication is to ensure you are who you say you are and can use the application freely in one session without having to show your credentials&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Authorization is ensuring you, and other users, are authorized to have access to what you are supposed to, or not supposed to.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Authentication uses sessions &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Authorize uses before_action and skip_before_action&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  To conclude
&lt;/h2&gt;

&lt;p&gt;Grasping the fundamental concepts of Authentication and Authorization in Rails is crucial for building secure and functional web applications. The purpose of Authorization is to define what users are allowed to do within the application and ensure users have appropriate permissions for specific actions and resources. Meanwhile, Authentication is for verifying the identity of users and ensuring they are who they claim to be. &lt;/p&gt;

&lt;p&gt;Utilizing both Authentication and Authorization in your web applications will allow you to protect your application from unauthorized access and guard sensitive user data from cybercrime. Wherever you are in your software journey, understanding the distinction between Authorization and Authentication, as well as their implementation is extremely important to building secure software.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Mastering ActiveRecord Associations in Ruby: A Comprehensive Guide</title>
      <dc:creator>samanthamarberger</dc:creator>
      <pubDate>Tue, 23 May 2023 21:10:36 +0000</pubDate>
      <link>https://dev.to/samanthamarberger/mastering-activerecord-associations-in-ruby-a-comprehensive-guide-50go</link>
      <guid>https://dev.to/samanthamarberger/mastering-activerecord-associations-in-ruby-a-comprehensive-guide-50go</guid>
      <description>&lt;h2&gt;
  
  
  What are database associations?
&lt;/h2&gt;

&lt;p&gt;Database associations are necessary for Ruby applications to manage the relationships between database tables. The associations establish relationships between related tables allowing you to properly link the crossover data within tables. Database associations also allow you to easily retrieve data that is related. With well-defined associations, information from one table can be easily obtained through another table. Along with this, the established relationships make handling CRUD operations and different tasks much more efficient. Lastly, complex relationships also become much easier to handle through database associations, by utilizing many of the different relationships managing your data becomes much more efficient. So with all that said, let's get into using ActiveRecord associations to show how easy managing database relationships can be.&lt;/p&gt;

&lt;p&gt;ActiveRecord is a Ruby gem that was created to simplify the binding process between tables within a database. It allows us to use keywords to create relationships rather than building out our own object-relational mapper and manually writing complex SQL. You see, ActiveRecord generated your SQL code behind the scenes allowing you to focus on your application rather than writing out code for your database associations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding ActiveRecord Associations
&lt;/h2&gt;

&lt;p&gt;Let's create a scenario. We want to create a web application to help us work out. To do this, we need to create a data table with all of the major muscle groups and a separate data table of exercises; each table has many different attributes.&lt;/p&gt;

&lt;p&gt;Let's do this by creating each class using ActiveRecord:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MuscleGroup&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;

&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Exercise&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;

&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once these are created, you are going to create a migration for each table by running: &lt;br&gt;
&lt;code&gt;&lt;br&gt;
bundle exec rake db:create_migration NAME=create_muscle_groups&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
and&lt;br&gt;
&lt;code&gt;&lt;br&gt;
bundle exec rake db:create_migration NAME=create_exercises&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This migration will create a .rb file with a timestamp at the beginning where you can create your table with all of its attributes. The timestamp is an important aspect of ActiveRecord because it ensures that the migrations are running in the intended order. &lt;/p&gt;

&lt;p&gt;In your migration file you can create your tables like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CreateMuscleGroups&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Migration&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;6.1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;change&lt;/span&gt;
    &lt;span class="n"&gt;create_table&lt;/span&gt; &lt;span class="ss"&gt;:muscle_groups&lt;/span&gt; &lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:image_url&lt;/span&gt;
    &lt;span class="k"&gt;end&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CreateExercises&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Migration&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;6.1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;change&lt;/span&gt;
    &lt;span class="n"&gt;create_table&lt;/span&gt; &lt;span class="ss"&gt;:exercises&lt;/span&gt; &lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:image_url&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:how_to_do&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;integer&lt;/span&gt; &lt;span class="ss"&gt;:muscle_group_id&lt;/span&gt;
    &lt;span class="k"&gt;end&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order to migrate the table, run &lt;code&gt;bundle exec rake db:migrate&lt;/code&gt; after you add a new table or make changes to your table. &lt;/p&gt;

&lt;p&gt;You will notice the attribute &lt;code&gt;muscle_group_id&lt;/code&gt;. This is our &lt;b&gt;foreign key&lt;/b&gt;. Let's define foreign key and primary key.&lt;/p&gt;

&lt;h5&gt;
  
  
  Primary key
&lt;/h5&gt;

&lt;p&gt;A primary key is a unique identifier for each row in a database table. This provides the uniqueness of the key so that each case can be distinguished. Examples of this would be things like &lt;code&gt;id&lt;/code&gt;.&lt;/p&gt;

&lt;h5&gt;
  
  
  Foreign key
&lt;/h5&gt;

&lt;p&gt;A foreign key is an identifier that refers to the primary key in another table. This establishes the relationship between the two tables. An example of this is the &lt;code&gt;muscle_group_id&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Because of this foreign key, we now have a row in the exercise table that indicates, through the muscle group id, which muscle group the exercise &lt;code&gt;belongs_to&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;In order to best make use of these tables, we need to form a relationship. Using ActiveRecord we can very easily do so through one of the types of associations this is the &lt;code&gt;has_many&lt;/code&gt; and &lt;code&gt;belongs_to&lt;/code&gt; association. Each major muscle group &lt;code&gt;has_many&lt;/code&gt; exercises and each exercise &lt;code&gt;belongs_to&lt;/code&gt; a muscle group.&lt;br&gt;
To form this relationship, we would need to use these keywords in the class components for those tables. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MuscleGroup&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:exercises&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Exercise&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
    &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:muscle_group&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This indicates to ruby the relationship between muscle groups and exercises. As you can see, the &lt;code&gt;has_many&lt;/code&gt; keyword is followed by the pluralized class. That is because there are many exercises whereas, the &lt;code&gt;belongs_to&lt;/code&gt; keyword is followed by a singular class because there is only one muscle group for many of the exercises. &lt;/p&gt;

&lt;h2&gt;
  
  
  Seeding data and testing my code
&lt;/h2&gt;

&lt;p&gt;All of these relationships are great; however, what if we want to test them? We need some data. You can create mock data in db/seeds.rb. Let's go back to our one-to-many relationship and create a muscle group and a couple of exercises within the seeds.rb file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="no"&gt;MuscleGroup&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Legs"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;image_url: &lt;/span&gt;&lt;span class="s2"&gt;"https://tse3.mm.bing.net/th?id=OIP.CCaTj7B5HI0e7pIotjn4PAHaE7&amp;amp;pid=Api&amp;amp;P=0&amp;amp;h=180"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="no"&gt;Exercise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Back Squat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;image_url: &lt;/span&gt;&lt;span class="s2"&gt;"https://julielohre.com/wp-content/uploads/2017/11/Barbell-Back-Squat.jpg"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="ss"&gt;how_to_do: &lt;/span&gt;&lt;span class="s2"&gt;"Hold the barbell on your shoulders.  Keeping your back straight, squat down until the angel of your legs reaches 90 degrees or greater. Press up until you reach starting position."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;muscle_group_id: &lt;/span&gt;&lt;span class="no"&gt;MuscleGroup&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Legs"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;Exercise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Calf Raise"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;image_url: &lt;/span&gt;&lt;span class="s2"&gt;"https://i0.wp.com/bootcampmilitaryfitnessinstitute.com/wp-content/uploads/2018/02/Exercise-Calf-Raises-1.jpg?ssl=1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="ss"&gt;how_to_do: &lt;/span&gt;&lt;span class="s2"&gt;"Start with your feet flat on the ground.  Raise up on your toes as far as you can, squeezing the muscles in your calves.  Return to starting position."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="ss"&gt;muscle_group_id: &lt;/span&gt;&lt;span class="no"&gt;MuscleGroup&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Legs"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to test my data, I want to run &lt;code&gt;bundle exec rake db:seed&lt;/code&gt;. This will seed all of my mock data and I can play around with my code and make sure it works!&lt;/p&gt;

&lt;p&gt;To get to the console let's run &lt;code&gt;bundle exec rake console&lt;/code&gt;&lt;br&gt;
We can now interact with the console and test our code using... ActiveRecord methods!&lt;/p&gt;
&lt;h2&gt;
  
  
  ActiveRecord methods
&lt;/h2&gt;

&lt;p&gt;There is a long list of ActiveRecord methods that allow us to interact with the database, here are a few and what they do: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Creating Records:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;.create: Creates a new record and saves it to the database.&lt;br&gt;
.new: Creates a new record but does not save it to the database.&lt;br&gt;
.save: Saves changes to an existing record or creates a new record and saves it.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Retrieving Records:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;.find: Finds a record by its primary key (usually id).&lt;br&gt;
.find_by: Finds the first record that matches the specified conditions.&lt;br&gt;
.where: Retrieves records that match the specified conditions.&lt;br&gt;
.first: Retrieves the first record from the database.&lt;br&gt;
.last: Retrieves the last record from the database.&lt;br&gt;
.all: Retrieves all records from the database.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Updating Records:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;.update: Updates attributes of a record and saves it to the database.&lt;br&gt;
.save: Saves changes to an existing record.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Deleting Records:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;.destroy: Deletes a record from the database.&lt;/p&gt;
&lt;h4&gt;
  
  
  Examples:
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="no"&gt;Exercise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Pull-up"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;image_url: &lt;/span&gt;&lt;span class="s2"&gt;"https://tse4.mm.bing.net/th?id=OIP.3fI1p5ikgmNfCWjyMGPpAwHaHa&amp;amp;pid=Api&amp;amp;P=0&amp;amp;h=180"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="ss"&gt;how_to_do: &lt;/span&gt;&lt;span class="s2"&gt;"Start hanging from the bar with your arms shoulder width apart.  Pull your body upward until your chin is over the bar.  Lower yourself back down to the starting position."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="ss"&gt;muscle_group_id: &lt;/span&gt;&lt;span class="no"&gt;MuscleGroup&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="s2"&gt;"Back"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="no"&gt;Exercises&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="c1"&gt;#&amp;lt;MuscleGroup:0x0000000109837728&lt;/span&gt;
 &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;#id: 3,&lt;/span&gt;
 &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;#name: "Legs",&lt;/span&gt;
 &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;#image_url: "https://tse3.mm.bing.net/th?=&amp;gt;#id=OIP.CCaTj7B5HI0e7pIotjn4PAHaE7&amp;amp;pid=Api&amp;amp;P=0&amp;amp;h=180"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;These are just a few but give you a lot of power to interact with your database.&lt;/p&gt;
&lt;h2&gt;
  
  
  But what if I wanted to get really specific about the muscle groups?
&lt;/h2&gt;

&lt;p&gt;Many exercises actually hit different muscle groups. What then? Well, we can create a &lt;strong&gt;Many to Many relationship &lt;/strong&gt;.&lt;br&gt;
This is when the &lt;code&gt;has_many :through&lt;/code&gt; keyword comes in. Let's make a new database table called SecondaryMuscle, this will be our JOIN table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SecondaryMuscle&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;

&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and run &lt;br&gt;
&lt;code&gt;&lt;br&gt;
bundle exec rake db:create_migration NAME=create_secondary_muscles&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
We now have created a migration and can create the table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CreateSecondaryMuscles&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Migration&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;6.1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;change&lt;/span&gt;
    &lt;span class="n"&gt;create_table&lt;/span&gt; &lt;span class="ss"&gt;:secondary_groups&lt;/span&gt; &lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:name&lt;/span&gt;
      &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;string&lt;/span&gt; &lt;span class="ss"&gt;:image_url&lt;/span&gt;
    &lt;span class="k"&gt;end&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now will add/ change our associations using the secondary muscles JOIN table. &lt;/p&gt;

&lt;p&gt;The SecondaryMuscles table JOINs the two together in a many-to-many association:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SecondaryMuscle&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
  &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:muscle_group&lt;/span&gt;
  &lt;span class="n"&gt;belongs_to&lt;/span&gt; &lt;span class="ss"&gt;:exercise&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The MuscleGroups associations now become:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MuscleGroup&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:secondary_muscles&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:exercises&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;through: :secondary_muscles&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Exercises associations have become:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Exercise&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:secondary_muscles&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:muscle_groups&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;through: :secondary_muscles&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, through a small amount of code, you have formed relationships that give you easily accessible information from each table. &lt;/p&gt;

&lt;h2&gt;
  
  
  ActiveRecord Macros
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;has_many&lt;/code&gt;, &lt;code&gt;belongs_to&lt;/code&gt;, and &lt;code&gt;has_many :through&lt;/code&gt; are all ActiveRecord macros. There are a few other types that I won't be going into but could be helpful to know. These macros are:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;has_one&lt;/code&gt; - this defines a one-to-one association between two models. This is done by setting up an association with a foreign key in one table that references the primary key in the other, very similar to one-to-many.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;has_and_belongs_to_many&lt;/code&gt; - this defines a many-to-many association between two tables without having to create an intermediate model, for example, no need for our SecondaryMuscle model. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;has_one :through&lt;/code&gt;- this defines a one-to-one association through an intermediate model. Very similar to using the &lt;code&gt;has_many :through&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To conclude, using ActiveRecord will make your life much easier as a ruby developer. It will allow you to spend more time creating your web application and less time trying to create relationships using handwritten SQL. If you want to dive even deeper, please take a look at &lt;a href="https://guides.rubyonrails.org/active_record_basics.html"&gt;Link to ruby on rails: ActiveRecord&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>activerecord</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>useState Hook: A staple that every React user should know how to use</title>
      <dc:creator>samanthamarberger</dc:creator>
      <pubDate>Wed, 08 Feb 2023 05:31:27 +0000</pubDate>
      <link>https://dev.to/samanthamarberger/usestate-hook-a-staple-that-every-react-user-should-know-how-to-use-37g1</link>
      <guid>https://dev.to/samanthamarberger/usestate-hook-a-staple-that-every-react-user-should-know-how-to-use-37g1</guid>
      <description>&lt;h2&gt;
  
  
  So you want to add dynamic functionality to your web application using React?
&lt;/h2&gt;

&lt;p&gt;Let's talk about the &lt;strong&gt;useState&lt;/strong&gt; hook. The &lt;strong&gt;useState&lt;/strong&gt; hook is a function that can be imported from react. This function allows you to set a component's state, or value, but the value can be changed by some type of action on the users end. This change also causes an automatic re-render of the page, allowing information on the DOM to be updated anytime the state variable is changed! &lt;/p&gt;

&lt;h1&gt;
  
  
  How do I import the useState hook?
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;You must import it from React.&lt;/li&gt;
&lt;li&gt;Call and initialize your state variable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Take a look at the code below!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

function Counter() {
    const [counter, setCounter] = useState(0);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line of code here imports the ability to use state, the line of code within the counter function is initializing the variable. The variable is set as an object, including the variable name, as well as the setter function, in this case "setCounter". That setter function is what is used to update/ change the counter variables value. &lt;/p&gt;

&lt;p&gt;In the code above, I created a function component that outputs the counter value, which as of now is 0. When I initialized my counter variable it was set with a const. Even though the value of the variable can change, const is used rather than let because &lt;strong&gt;useState&lt;/strong&gt; is an updating function. The variable does not get reassigned through the "=" operator, but rather updated by using the setter function like so.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setCounter(1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The counter variable would now return "1". &lt;/p&gt;

&lt;p&gt;The "counter" is the container for the value, in this case 0. The second variable, "setCounter" is the updating function. Both are required when using the &lt;strong&gt;useState&lt;/strong&gt; hook. &lt;/p&gt;

&lt;h1&gt;
  
  
  When to not use state!
&lt;/h1&gt;

&lt;p&gt;The &lt;strong&gt;useState&lt;/strong&gt; hook is a very powerful tool; however, if it is used too often and in the wrong circumstances your code can get buggy quickly and it would be a painful debugging process. &lt;/p&gt;

&lt;p&gt;Here are three general things to check for to determine if state would be useful or not. They are found in &lt;a href="https://reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state" rel="noopener noreferrer"&gt;Thinking in React&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;1. Does your state variable get passed as a prop between components?&lt;/em&gt;&lt;br&gt;
If it is, it is likely not going to be state. State should only be updated and used within the component it is declared in.&lt;br&gt;
&lt;em&gt;2. Is your state variable truly a constant?&lt;/em&gt;&lt;br&gt;
If your state does not change and there is no need for a set function to update your state variable, you do not need a state variable. A simple constant will do!&lt;br&gt;
&lt;em&gt;3. Can your value be computed from any other state or props in the component?&lt;/em&gt;&lt;br&gt;
Basically, don't over use state. If you already have an existing state and you want to create another state variable, make sure it is not one that can be derived from your original state.  &lt;/p&gt;
&lt;h1&gt;
  
  
  Examples of using state:
&lt;/h1&gt;

&lt;p&gt;I am going to discuss two different situations in which using the &lt;strong&gt;useState&lt;/strong&gt; hook would be helpful. The first is a basic counter function to help us get a better understanding of &lt;strong&gt;useState&lt;/strong&gt;. The second will be an example from a recent project of mine where we will go over using &lt;strong&gt;useState&lt;/strong&gt; with arrays.&lt;/p&gt;
&lt;h2&gt;
  
  
  The simple counter function:
&lt;/h2&gt;

&lt;p&gt;Let's create a counter function that allows you to increase your output number by one each time a "plus one" button is pressed.  This set up is shown above when I go over how to import &lt;strong&gt;useState&lt;/strong&gt; but I will add a few more things and discuss it once more below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Counter() {
    const [counter, setCounter] = useState(0);

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;h1&amp;gt;{counter}&amp;lt;/h1&amp;gt;
            &amp;lt;button&amp;gt;+1&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the setup above, I have a variable being set, using the &lt;strong&gt;useState&lt;/strong&gt; hook, to 0. I am returning the counter value as well as a  button that says "+1". This button does not yet have functionality, let's add some!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; function addOne() {
        setCounter(counter + 1);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I built a function that when called upon takes the counter variable and updates it to the assigned counter variable plus one. When I call the setter function, in this case "setCounter", the page re-renders and the DOM is automatically updated. I need to call the setCounter() function, this will be done by creating an onClick for my button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={addOne}&amp;gt;+1&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the setCounter function is called and the value is updated!&lt;/p&gt;

&lt;h2&gt;
  
  
  Using useState with arrays
&lt;/h2&gt;

&lt;p&gt;Arrays can be updated using the &lt;strong&gt;useState&lt;/strong&gt; hook as well. In a recent project of mine I created a web application that allows me to store all of my favorite paintings and add paintings to my collection. The paintings are stored on a server; however, I want them to be stored in an array. To do this, I must first use the &lt;strong&gt;useState&lt;/strong&gt; hook to define the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const [paintings, setPaintings] = useState([]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I created a painting variable and a setter function for that variable and I set it to an empty array.&lt;/p&gt;

&lt;p&gt;Through a fetch request I was able to pull the information from my server and use my setter function to put it into an array. I don't want to distract from the &lt;strong&gt;useState&lt;/strong&gt; hook functionality, so I am going to simplify and make an array of paintings and use my setter function to update the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const paintingsArray = ["Starry Night", "The Scream", "Royal Red and Blue"];

setPaintings(paintingsArray);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now my paintings array is no longer an empty array, but an array of three values.&lt;/p&gt;

&lt;p&gt;Let's say I wanted to add another painting to the array. I simply need to use the spread operator, making a copy of my paintings, and add the new element to that array. I would then call the setPaintings function and give it the new array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;newPaintingsArray = [...paintings, newPainting];
setPaintings(newPaintingsArray);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The use of the setter function caused a re-render leading to an automatic update of the DOM. This allows my web application to update the paintings right away without any refreshing from the user.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting state is an asynchronous process.
&lt;/h2&gt;

&lt;p&gt;Because setting state is asynchronous, the function of setting the state will not be immediately executed. React waits until other processes or functions are completed before it changes state. This is an important thing to note; if you try to set state more than once within a function, the output will likely not be your desired output. &lt;/p&gt;

&lt;p&gt;For example, say we have a button on our counter function that when clicked adds 1 to the value and then multiplies it by 5. Let's see what would happen if you put those two commands separately in the same function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; function addOneMultiplyFive() {
        setCounter(counter + 1);
        setCounter(counter * 5);
    }

return (
        &amp;lt;div&amp;gt;
            &amp;lt;h1&amp;gt;{counter}&amp;lt;/h1&amp;gt;
            &amp;lt;button&amp;gt;+1&amp;lt;/button&amp;gt;
            &amp;lt;button onClick={addOneMultiplyFive}&amp;gt;Add one and multiply by 5&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    );

// If I click the "Add one and multiply by 5 button"
// =&amp;gt; 0

// If I click the "+1" button first and then the "Add one and multiply by 5" button
// =&amp;gt; 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;React is not updating state in between the addition of 1 and the multiplying of 5 in the "addOneMultiplyFive" function. Therefore, the counter value being multiplied by 5 is the counter value before the button was clicked. &lt;/p&gt;

&lt;p&gt;Well, there you have it! Hopefully you have a better understanding of how and when to use state variables. Good luck with your next React project!&lt;/p&gt;

</description>
      <category>docker</category>
      <category>langchain</category>
      <category>bunjs</category>
      <category>tooling</category>
    </item>
    <item>
      <title>Functions: How to clean up your code</title>
      <dc:creator>samanthamarberger</dc:creator>
      <pubDate>Mon, 07 Nov 2022 20:13:51 +0000</pubDate>
      <link>https://dev.to/samanthamarberger/functions-how-to-clean-up-your-code-8p</link>
      <guid>https://dev.to/samanthamarberger/functions-how-to-clean-up-your-code-8p</guid>
      <description>&lt;p&gt;My first introduction to functions was a doozy... When I was learning how to code, it was all done within a main function. That made sense to me, the code was written in the exact order that it was performed in. Next thing I know, they're throwing functions at me and telling me it will be helpful. It was not until the second time going over functions when I realized how helpful they really are! &lt;/p&gt;

&lt;p&gt;The two different segments of code below have the same outputs; however, the second, through functions, is shorter and much easier to understand.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Math:" );
let a = 1 + 2;
console.log(`1 + 2 = ${a}`);
a = 2 + 2;
console.log(`2 + 2 = ${a}`);
a = 3 + 2;
console.log(`3 + 2 = ${a}`);
a = 1 * 2;
console.log(`1 * 2 = ${a}`);
a = 2 * 2;
console.log(`2 * 2 = ${a}`);
a = 3 * 2;
console.log(`3 * 2 = ${a}`);
a = 1 - 2;
console.log(`1 - 2 = ${a}`);
a = 2 - 2;
console.log(`2 - 2 = ${a}`);
a = 3 - 2;
console.log(`3 - 2 = ${a}`);
a = 1 / 2;
console.log(`1 / 2 = ${a}`);
a = 2 / 2;
console.log(`2 / 2 = ${a}`);
a = 3 / 2;
console.log(`3 * 2 = ${a}`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above is long and extremely repetitive, functions can provide clarity and minimize redundancy, as seen below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a, b){
  return `${a} + ${b} = ${a + b}`;
}

function subtract(a, b) {
  return `${a} - ${b} = ${a - b}`;
}

function multiply (a, b) {
  return `${a} * ${b} = ${a * b}`;
}

function divide (a, b) {
  return `${a} / ${b} = ${a / b}`;
}
console.log("Math:");
console.log(add(1,2));
console.log(add(2,2));
console.log(add(3,2));
console.log(multiply(1,2));
console.log(multiply(2,2));
console.log(multiply(3,2));
console.log(subtract(1,2));
console.log(subtract(2,2));
console.log(subtract(3,2));
console.log(divide(1,2));
console.log(divide(2,2));
console.log(divide(3,2));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code, consisting of four functions, allows my main code to be shortened, and due to proper function naming, easy to read. This code could be shortened even more using loops (which I will discuss in another post). &lt;/p&gt;

&lt;h3&gt;
  
  
  Let's break this code down
&lt;/h3&gt;

&lt;h4&gt;
  
  
  We will start by diving into our add function.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a, b){
  return `${a} + ${b} = ${a + b}`;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As seen above, there are a few things that are included in this function. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;There is a function keyword. The function keyword tells javascript that you are creating a function. This is important; however, function keywords are not necessary, which I will explain later. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A clear function name is provided to allow others to understand what your function is supposed to do. Others looking at your code should know what the function does just from its name. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parameters are the variables found within the (). By including parameters, you can pass values to the function, which is what help make functions such a powerful tool. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Curly braces! These are important for the function in the example above; however, I will show examples below where curly braces are not required. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Return keyword. This keyword is also not always required, but for this example, without it, your functions would return 'undefined'. This is because the function has to return something and if you're not giving it anything to return, it will think that you want it to return nothing.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The return keyword is useful if you want to take the output of a function and use it again later. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(a, b){
  return a + b;
}
function divide(a, b){
  return a / b;
}

const addedNum = add(2,4);
const dividedNum = divide(addedNum, 2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By using the return keyword in my add function, I was able to assign the output to a variable and use it in another function. &lt;/p&gt;

&lt;h4&gt;
  
  
  Let's now talk about calling the function
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add(1,2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To call the function is quite simple, all you need is the function name, and the parameter values you want to pass into the function. &lt;/p&gt;

&lt;h2&gt;
  
  
  Different ways to define functions
&lt;/h2&gt;

&lt;p&gt;There are three ways to to write a function in javascript. &lt;/p&gt;

&lt;h3&gt;
  
  
  1. Function declaration
&lt;/h3&gt;

&lt;p&gt;Function declaration is what was being used above. &lt;br&gt;
This way of defining a function is useful because it allows you to invoke the function before it is defined, otherwise known as hoisting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add(2,4)
function add(a, b){
  return a + b;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though I am calling the function before I have declared it, the add call will still execute.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Function expressions
&lt;/h3&gt;

&lt;p&gt;This is defining a function by using a variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiply = function (a, b){
  return a * b;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example shows the same multiply function, but it is defined using function expression. &lt;/p&gt;

&lt;h3&gt;
  
  
  3. Arrow Functions
&lt;/h3&gt;

&lt;p&gt;Arrow function notation is great for making your code concise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiply = (a, b) =&amp;gt; a * b;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This may be a little difficult to read at first, at least it was for me, but let me break it down. &lt;br&gt;
The arrow notation can be defined using a variable, similar to function expression. However, it skips over all the additional keywords and allows you to write your function definition in one line. The parameters are entered in after the "=" and the arrow points to what will be returned. &lt;br&gt;
As you can see, no return key word is required when using arrow function notation, otherwise known as implicit return.&lt;br&gt;
Curly braces are not required when only one line of code is necessary; however, if more lines are required, the curly braces are needed to enclose everything after the arrow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const greetings = (userName, helloGreeting, goodbyeGreeting) =&amp;gt; {
  console.log(`${helloGreeting}, ${userName}, it is nice to meet you!`);
  console.log(`${goodbyeGreeting}, ${userName}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, I had to use curly braces because my return code was longer than two lines.&lt;/p&gt;

&lt;h2&gt;
  
  
  Callback Functions
&lt;/h2&gt;

&lt;p&gt;The last concept that I wanted to touch on was one of the hardest things for me to understand. I did a lot of research to try and figure out how callback functions worked, but ultimately it came down to me utilizing callback functions in my code that made me understand.&lt;/p&gt;

&lt;p&gt;A callback function is a function that is being called within another function, this could be an anonymous function, or a function that you had previously defined. It is called a callback function because the function is not executed right away, it is called back to be used at a later time. Let me show you some examples!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const greeting = (userName, callbackFunction) =&amp;gt; {
  console.log(`Hello, ${userName}, it is nice to meet you!`);
  callbackFunction();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here you can see I did an arrow notation function called greeting (similar to the previous example). This greeting function takes a callback function as a parameter, and executes it when it is later invoked at the end of the greeting function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function iAmCallback() {
  console.log(`This is the callback Function`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the callback function definition. When used as the callback parameter, calling the greeting function will output "This is the callback Function".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;greeting("samuel", iAmCallback);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, this is how I call the greeting function. I pass it the name, and then the function I want to callback to be invoked when the greeting function is executed. When calling a function and passing in a callback function, it is important to remember to not immediately invoke your callback function by adding () after putting the callback function in as a parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output:
Hello, samuel, it is nice to meet you!
This is the callback Function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now using a callback function in this manner is useful when the callback function needs to be invoked multiple times. If the callback function is only used once, you can do an anonymous callback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myArray = ["item1", "item2", "item3"]; 

myArray.forEach(() =&amp;gt; {
  console.log('This is the anonymous callback Function');
}) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, I created an array and iterated through it using the forEach method. For each of the items in the array, the anonymous callback function is performed. The anonymous function is written using arrow notation, taking in no parameters but simply returning the output shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output:
This is the callback anonymous Function
This is the callback anonymous Function
This is the callback anonymous Function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function was called three times!&lt;/p&gt;

&lt;h2&gt;
  
  
  I hope this post has helped you to realize how useful functions can be!
&lt;/h2&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>functions</category>
    </item>
  </channel>
</rss>
