<?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 Maria Coitinho on Medium]]></title>
        <description><![CDATA[Stories by Maria Coitinho on Medium]]></description>
        <link>https://medium.com/@brasildu?source=rss-772a25b2a395------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H0Kr5w4aNkqoV_j2</url>
            <title>Stories by Maria Coitinho on Medium</title>
            <link>https://medium.com/@brasildu?source=rss-772a25b2a395------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:49:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brasildu/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[Understanding Machine Learning: Main Concepts]]></title>
            <link>https://medium.com/@brasildu/understanding-machine-learning-main-concepts-40a57667f123?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a57667f123</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 07:07:53 GMT</pubDate>
            <atom:updated>2023-03-04T07:07:53.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning is one of the most significant developments in the field of artificial intelligence. It is a method of teaching machines to learn from data, without being explicitly programmed. In other words, it is about creating algorithms that enable machines to recognize patterns in data and make decisions based on that data. In this blog post, we’ll explore the main concepts of machine learning and why it is such a powerful tool in today’s world.</p><h3>Supervised Learning</h3><p>Supervised learning is the most common type of machine learning. It involves feeding the machine with labeled data, i.e., data that has already been categorized. The machine learns to recognize patterns in the data and can then make predictions or decisions based on new, unlabeled data.</p><p>For example, let’s say we want to teach a machine to recognize handwritten digits. We can provide it with a set of labeled data, where each digit is labeled with its corresponding numerical value. The machine can then learn to recognize the patterns in the data and make accurate predictions about new, unlabeled data.</p><h3>Unsupervised Learning</h3><p>Unsupervised learning involves feeding the machine with unlabeled data. The machine must identify patterns in the data on its own, without any prior knowledge. This type of learning is often used in clustering, where the machine groups similar data points together.</p><p>For example, let’s say we have a large set of customer data that we want to group into different segments based on their behavior. We can provide the machine with the data and let it identify patterns and group the customers into segments.</p><h3>Reinforcement Learning</h3><p>In reinforcement learning, the machine is given a task to perform and is rewarded or punished based on how well it performs the task. The machine learns from its mistakes and improves over time.</p><p>For example, let’s say we want to teach a machine to play a game. We can provide it with a set of rules and let it play the game. The machine is rewarded when it makes the right moves and penalized when it makes the wrong moves. Over time, the machine learns to make the right moves and becomes better at the game.</p><h3>Deep Learning</h3><p>Deep learning is a subset of machine learning that involves the use of neural networks to process and analyze data. It is inspired by the structure and function of the human brain and is used in image and speech recognition, natural language processing, and more.</p><p>For example, let’s say we want to teach a machine to recognize images of cats and dogs. We can provide it with a large set of labeled data, where each image is labeled as either a cat or a dog. The machine can then learn to recognize the patterns in the images and make accurate predictions about new images.</p><h3>Why Machine Learning Matters</h3><p>Machine learning has become increasingly important in today’s world for several reasons. First, it has the ability to automate tasks and make them more efficient, saving time and money. Second, it can help us make better decisions by analyzing large amounts of data and providing insights that we may have otherwise missed. Finally, machine learning is driving innovation in many industries, from healthcare to finance to transportation.</p><h3>Conclusion</h3><p>Machine learning is a powerful tool that has the potential to transform the way we live and work. By understanding its main concepts, we can begin to appreciate its value and the impact it is having on our world. As technology continues to evolve, we can expect to see even more advancements in machine learning and artificial intelligence, and it is up to us to embrace these changes and use them to create a better future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a57667f123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails Serializers: Introduction]]></title>
            <link>https://medium.com/@brasildu/ruby-on-rails-serializers-introduction-6b97fc15dcbe?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b97fc15dcbe</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[serialization]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 09:26:58 GMT</pubDate>
            <atom:updated>2023-02-20T09:27:19.670Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever worked with Ruby on Rails, you know that it’s a powerful web framework that makes building complex applications much easier. One of the key features that makes Rails so useful is its built-in support for serializers, which help you manage data and send it to clients in the format they need.</p><p>In this post, we’ll take a friendly look at serializers in Rails, discussing what they are, why you might want to use them, and how to use them effectively.</p><h3>What are Serializers?</h3><p>Simply put, serializers are classes that help you convert complex data structures into a format that can be easily sent over the network. For example, you might have an object in your Rails application that has a lot of associated data, such as a user with a list of posts, comments, and likes. When you want to send that user’s data to a client, you might not want to send all that extra data — it’s inefficient and can slow down your application.</p><p>That’s where serializers come in. A serializer takes the user object and converts it into a simpler, more streamlined format that can be sent over the network. This might involve removing unnecessary data, transforming data into a different format, or adding metadata that helps the client understand the data.</p><h3>Why Use Serializers?</h3><p>There are a few key reasons why you might want to use serializers in your Rails application:</p><ol><li><strong>Performance</strong>: As we mentioned earlier, sending large amounts of data over the network can be slow and inefficient. By using serializers to streamline your data, you can improve the performance of your application.</li><li><strong>Flexibility</strong>: With serializers, you can easily customize the data that’s sent to different clients. For example, you might want to send different data to a mobile app than you would to a web browser. Serializers make it easy to adapt to different clients without having to write custom code for each one.</li><li><strong>Security</strong>: By limiting the amount of data that’s sent to clients, you can reduce the risk of security vulnerabilities. For example, if you’re sending user data to a client, you might want to remove sensitive information such as passwords or email addresses.</li></ol><h3>Using Serializers in Rails</h3><p>Now that we know what serializers are and why we might want to use them, let’s look at how to use them in a Rails application. Here’s a basic example:</p><pre>class UserSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :name, :email<br>end</pre><p>In this example, we’re defining a serializer for a user object. The attributes method specifies which attributes of the object we want to include in the serialized data.</p><p>To use this serializer, we can call it from a controller:</p><pre>class UsersController &lt; ApplicationController<br>  def show<br>    user = User.find(params[:id])<br>    render json: user, serializer: UserSerializer<br>  end<br>end</pre><p>In this controller, we’re finding a user object and rendering it as JSON using our UserSerializer. The resulting data will only include the id, name, and email attributes.</p><h3>Conclusion</h3><p>Serializers are a powerful tool in the Ruby on Rails toolbox. By using serializers, you can streamline your data, improve performance, and customize the data that’s sent to clients. With the right use of serializers, you can build fast, secure, and flexible applications that are a joy to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b97fc15dcbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record Associations in Ruby on Rails: Explained with Examples]]></title>
            <link>https://medium.com/@brasildu/active-record-associations-in-ruby-on-rails-explained-with-examples-999dc897d8af?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/999dc897d8af</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 08:53:03 GMT</pubDate>
            <atom:updated>2023-02-20T08:56:14.615Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a Ruby on Rails application, you’re likely working with databases and need to create associations between different models. Fortunately, Rails provides a convenient way to manage these relationships with Active Record associations. In this blog post, we’ll explore three common types of associations: has_one, has_many through, and belongs_to.</p><h3>has_one association</h3><p>The has_one association is used when a model has only one associated record in another model. For example, let&#39;s say you have a User model that has one Profile model. Here&#39;s how you would define the association:</p><pre>class User &lt; ApplicationRecord<br>  has_one :profile<br>end<br><br>class Profile &lt; ApplicationRecord<br>  belongs_to :user<br>end</pre><p>This creates a one-to-one association between the User and Profile models. You can use this association to access the associated Profile record from a User record, like so:</p><pre>user = User.find(1)<br>profile = user.profile</pre><h3>has_many through association</h3><p>The has_many through association is used when a model has many associated records in another model, but these associations are not direct. Instead, they go through a third model. For example, let&#39;s say you have a Doctor model that has many Patients through Appointments. Here&#39;s how you would define the association:</p><pre>class Doctor &lt; ApplicationRecord<br>  has_many :appointments<br>  has_many :patients, through: :appointments<br>end<br><br>class Appointment &lt; ApplicationRecord<br>  belongs_to :doctor<br>  belongs_to :patient<br>end<br><br>class Patient &lt; ApplicationRecord<br>  has_many :appointments<br>  has_many :doctors, through: :appointments<br>end</pre><p>This creates a many-to-many association between the Doctor and Patient models. You can use this association to access the associated Patient records from a Doctor record, like so:</p><pre>doctor = Doctor.find(1)<br>patients = doctor.patients</pre><h3>belongs_to association</h3><p>The belongs_to association is used when a model belongs to another model. For example, let&#39;s say you have a Comment model that belongs to a Post model. Here&#39;s how you would define the association:</p><pre>class Comment &lt; ApplicationRecord<br>  belongs_to :post<br>end<br><br>class Post &lt; ApplicationRecord<br>  has_many :comments<br>end</pre><p>This creates a one-to-many association between the Post and Comment models. You can use this association to access the associated Comment records from a Post record, like so:</p><pre>post = Post.find(1)<br>comments = post.comments</pre><h3>Conclusion</h3><p>Active Record associations are a powerful tool for managing relationships between models in Ruby on Rails. In this blog post, we’ve covered three common types of associations: has_one, has_many through, and belongs_to. By understanding these associations and how to use them, you&#39;ll be able to build more complex and dynamic applications with ease. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999dc897d8af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails — Validations]]></title>
            <link>https://medium.com/@brasildu/ruby-on-rails-validations-4fceb37c1795?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fceb37c1795</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 21:49:32 GMT</pubDate>
            <atom:updated>2023-01-30T21:53:45.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ruby on Rails: Validations</h3><p>You probably already crossed with many different websites that require some kind of data from the user. For example, when you need to sign up in order to have an account and being able to login as a user on Instagram, Facebook, etc.</p><p>We often see messages like ‘the username is not valid’ or ‘the username has already been taken’. Let’s see what happens if we try signing up to Instagram, with a username:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*EXq2kO-tCLEhonN-yQXEZQ.png" /></figure><p>We get an error message saying that the username is not available, meaning that there’s a user with this name already saved in the Instagram database.</p><p>This is just one example of how servers validate data sent from a user. But an API can verify any kind of information, like requiring a minimum number of characters in a comment or limiting it, requiring an input field to not be blank, etc. It all depends on the usage and how we want the data to be persisted on the server.</p><p>If you have an application that receives data from the client, you don’t want users to submit whatever they want, but limit and set data requirements. This is because we don’t want for example, duplicate data in our database, or data that is different from what is being requested in the client side.</p><p>But how does this transfer of information work and how do applications make sure that the type of data you are trying to send to the server is valid? With a Rails API, we have what it’s called Active Record <strong><em>validations</em></strong>.</p><h3>Rails API resource</h3><p>Let’s say that we have our Rails API set up with a resource generator — you can check <a href="https://medium.com/@brasildu/ruby-on-rails-generators-a747212177fa">this post</a> I made about generators — to create a <em>Student</em> resource. When generating a resource, we will have the following files created:</p><ul><li><em>students_controller.rb </em>(Controller);</li><li><em>student.rb</em> (Model);</li><li>The code <em>resources :students </em>that creates full CRUD routes, defined in <em>routes.rb</em>;</li><li>A migration file with attributes and types for each column of the database table (again, you can check my post on <a href="https://medium.com/@brasildu/ruby-on-rails-generators-a747212177fa">Rails Generators</a> if you need a more detailed explanation on how to generate a resource and create table columns with one line of code):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*VYKkRwIoxvUw9Tmrtlq9qw.png" /></figure><p>Having that all set up, we can start working with the student resource to allow only certain type of data to be persisted into our database, avoiding data that can possibly break our application.</p><h3>Active Record Validations</h3><p>We have two ways for validating data sent from the client: using the built-in Active Record validations or creating a custom validation — you can check all available built-in methods on the Rails Guides documentation <a href="https://guides.rubyonrails.org/active_record_validations.html">here</a>.</p><p>Before diving into examples for our <strong><em>Student</em></strong> resource, it’s important to understand where we would use validations in our application, as we might not necessarily need to validate all parts of it.</p><p>Let’s go over some validations commonly used in the real world — remembering that you can find more examples in the <a href="https://guides.rubyonrails.org/active_record_validations.html">Rails documentation</a> for the most different uses:</p><ul><li><strong>presence</strong> → checks that the data being sent from the client exists, for example when we have a form and we want to make sure that the user doesn’t submit a blank field;</li><li><strong>uniqueness</strong> → does not allow a client to send duplicate data, for example when a user tries creating a username that already exists (as we saw in the Instagram example in the beginning of this post);</li><li><strong>length </strong>→ sets a specific length for the data sent from the client, for example if we want to limit the length of a password that a user can create, to a minimum of characters.</li><li><strong>numericality</strong> → you can use this helper to validate that the attributes sent from the client are numbers, or restricting it to only accept integer types for example.</li></ul><h3>Where to define Validations?</h3><p>But where in our application should we define validations? The answer is in the <strong><em>Model. </em></strong>In our <em>models </em>folder we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*DqyfLIp7RCJON6Tc23teUQ.png" /></figure><p>Now you can check the top level model <em>application_record</em>.<em>rb:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*3Km4kXyXUP1M_buZPpvgwA.png" /></figure><p>The built-in validations are coming from <em>ActiveRecord::Base</em>, so we can use the validation methods in our <em>student </em>model, as Student inherits from <em>ApplicationRecord</em>.</p><h3>Triggering Validations</h3><p>There are some ways that we can trigger validations in our application using Active Record methods. But most importantly, let’s check what happens when we use these methods and we get <strong><em>invalid data</em></strong>:</p><ul><li>create → returns the object that was not successfully created, with the attribute of <em>created_at</em> of nil;</li><li>create! → raises an ActiveRecord::RecordInvalid exception;</li><li>save → returns false if it cannot successfully save the data;</li><li>save! → raises an ActiveRecord::RecordInvalid exception;</li><li>update → returns false if it cannot successfully update the data;</li><li>update! → raises an ActiveRecord::RecordInvalid exception;</li></ul><p>By default, Active Record doesn’t raise an exception when it cannot validate data, it will simply return false (for <em>update</em> and <em>save</em> methods) or the object (for the <em>create</em> method).</p><p>The methods listed above with a “!” (bang operator) are used for raising an Active Record exception, while the ones without the “!” will return something. Either way you are able to access the information of why the data was invalid.</p><p>In the next section, we are going to build some validations for our <em>Student </em>model and see how we can access information errors from it.</p><h3>Invalid Data Examples</h3><p>Going to our <em>student.rb</em> model file, we can require a few validations for the student attributes. But first, let’s take a look at what attributes a student has, in our migration file:</p><pre>class CreateStudents &lt; ActiveRecord::Migration[6.1]<br>  def change<br>    create_table :students do |t|<br>      t.string :name<br>      t.string :course<br>      t.text :teacher<br>      t.float :grade<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><blockquote>Note: Make sure to migrate the changes before running a rails server.</blockquote><p>When a student instance is being <strong>created</strong> or <strong>updated</strong> in the database, let’s suppose the following validations are going to be checked:</p><ul><li><strong>:name attribute</strong> → will require a student name to exist;</li><li><strong>:course attribute</strong> → will require a course to be at least 5 characters long;</li><li><strong>:grade attribute</strong> → will require a grade to be greater than 0.</li></ul><h4>Validation syntax</h4><p>Now that we have the logic for our attributes, we can starting writing it in the <em>student.rb</em> file:</p><pre>class Student &lt; ApplicationRecord<br>    validates :name, presence: true<br>end</pre><p>On the validation line, we are using the keyword <em>validates</em> and passing an attribute of a student name that we want to validate. Then on the same line, we are using the validation helper <em>presence</em>: and setting it to <em>true.</em></p><p>As we saw earlier on this post in the <strong>Active Record Validations section</strong>, the <em>presence</em> validator set to <em>true</em> makes sure that when an instance of a student is created/updated, before it is saved to the database, the student :<em>name</em> attribute should exist.</p><h4>Looking up validation errors</h4><p>Let’s try creating a student without passing a name attribute using the <em>interactive Ruby console (IRB)</em>:</p><pre>irb(main):003:0&gt; student = Student.create<br>=&gt; #&lt;Student id: nil, name: nil, course: nil, teacher: nil, grade: nil, created_at: nil, updated_at: nil&gt;</pre><p>We get back a student object but it was not created successfully. We can check that looking at the <em>created_at</em>, which has a <em>nil</em> value.</p><p>But how do we actually check what went wrong with the validation? We can do it chaining up the following methods to the student variable:</p><pre>irb(main):007:0&gt; student.errors.messages<br>=&gt; {:name=&gt;[&quot;can&#39;t be blank&quot;], :grade=&gt;[&quot;is not a number&quot;]}</pre><blockquote>Note: You are able to check all methods available for a student instance, chaining the .methods to a student object.</blockquote><p>We are now able to clearly understand what went wrong with the student instance we just tried to create — remember that the <em>create </em>method will trigger validation, different from <em>new</em>. We get a return value of a Ruby hash which we can access and for example, send back to the client side to be rendered.</p><p>Now let’s create a student passing it a name attribute:</p><pre>irb(main):001:0&gt; student = Student.create(name: &quot;John&quot;)<br>=&gt; #&lt;Student id: 8, name: &quot;John&quot;, course: nil, teacher: nil, grade: nil, created_at: &quot;2023-01-30 06:39:46...</pre><p>We have successfully created our student! Let’s add the other validations:</p><pre>class Student &lt; ApplicationRecord<br>    validates :name, presence: true # =&gt; requires the name to exist<br>    validates :course, length: {minimum: 5} # =&gt; requires length of 5 characters  <br>    validates :grade, numericality: {greater_than: 0} # =&gt; requires a grade to be greater than 0<br>end</pre><p>If you try creating or updating a student instance, you can notice that you will only be able to persist changes to the database if all attributes pass the specified validations.</p><h3>Controller Validations</h3><p>When working with a Rails API that receives requests from clients to change the database, validations are very useful. Imagine that you have a front end that frequently communicates with your server to change your students database table.</p><p>We don’t want the client to send invalid student data, so we are using the <em>student.rb </em>file to specify the validations we want our server to handle before any updates to the database are made:</p><pre>class Student &lt; ApplicationRecord<br>    validates :name, presence: true<br>    validates :course, length: {minimum: 5}<br>    validates :grade, numericality: {greater_than: 0}<br>end</pre><p>In our <em>students_controller.rb</em> file, whenever one of the methods that trigger validations is called (<em>create, create!, save, save!, update, update!</em>), the validations defined in our Student model will be triggered.</p><h3>Conclusion</h3><p>Validations are a set of essential tools that allows developers to use them on the server side, making sure that no invalid or malicious data is being persisted to the database. Writing some logic for validations in the Rails API model from the MVC (Model-View-Controller), makes you able to filter whatever type of data that is being sent from the client side before it even touches the database.</p><p>In this post, we:</p><ul><li>Went through a real world example of validations;</li><li>Set up a Rails API;</li><li>Defined some of the Active Record validations;</li><li>Where to define validations;</li><li>How do we trigger validations;</li><li>Saw the validations syntax and how to check its errors;</li><li>Validations in the controller.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fceb37c1795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails Controller Exceptions — ActiveRecord::RecordNotFound]]></title>
            <link>https://medium.com/@brasildu/rails-controller-exceptions-activerecord-recordnotfound-dbae5aa79cf9?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbae5aa79cf9</guid>
            <category><![CDATA[dat]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 10:37:15 GMT</pubDate>
            <atom:updated>2023-01-09T01:32:10.652Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails Controller Exceptions — ActiveRecord::RecordNotFound</h3><p>When we are using Rails to build a backend API, there are important steps to be followed in order to handle requests from clients and send back responses.</p><p>A Rails API is built with the MVC (Model-View-Controller) architectural pattern and has built-in generators that follow RESTful (Representational State Transfer) conventions.</p><p>Although Rails can be used to build a front and backend application, the most modern applications tend to use Rails particularly for creating API’s, along with React for the frontend development, for example.</p><p>In this post, we will be looking at a Rails API that is going to handle GET and DELETE requests from a client. The reason why we are choosing these HTTP verbs is that we will observe how a controller handles the communication with a Model to search up data sent from the client — through these requests, ending up not being found in the database.</p><p>First, we will be develop a basic Rails API from scratch so you can have a better understanding of the steps taken to get to the main purpose of this post: show how a controller manipulates non existent data and how it responds to a client.</p><p>As we are going to be creating a new Rails application, you can follow along with the steps below.</p><h3>rails new</h3><p>Let’s start creating a basic Rails API through the command line, with the name of <em>music</em>-<em>festival</em>, using the command:</p><pre>$ rails new music-festival --api --minimal -T</pre><p>Here we are creating a Rails application with the name <em>music-festival</em> and passing three flags. The <em>api</em> we are using to specify that we want to create a Rails API, which will only create the necessary files for that purpose, not including for example the View from MVC.</p><p>Rails is a very potent gem, so we are using the <em>minimal</em> flag here to make sure that Rails creates a basic app. Lastly, the <em>T</em> flag is used to tell Rails that we don’t want it to create any test setting for our application.</p><h3>Rails resource generator</h3><p>Now that we have created our application, let’s set up a database table, migrations, models, controllers and routes. But don’t worry, we are going to be able to build all this configuration using the rails <em>resource generator </em>in a single line command.</p><p>As our API is for a music festival, it makes sense for us to create a database table for bands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*2J6KK24RBIJUlvUDB7fUNw.png" /></figure><p>With the information above, we can now run the resource generator through the terminal:</p><pre>$ rails g resource bands name members concert_time:integer</pre><p>We can check the console log once the command is ran:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8AwrY9PPqdsZnMO0dSWgA.png" /></figure><p>Notice what happens: Rails invokes Active Record, creating 2 files. These two files are the database migration and the model, both inheriting from Active Record.</p><p>Next, it invokes the controller to create our <em>bands_controller.rb</em> file. Then we have our <em>resources :bands </em>created inside <em>config/routes.rb</em>, which automatically generates all REST routes for our server. We can check that doing:</p><pre>$ rails routes</pre><p>The command will display the routes available, which were created when we used the <em>resource</em> generator — if you are curious about this generator and others provided by Rails, you can check a post I made about it <a href="https://medium.com/@brasildu/ruby-on-rails-generators-a747212177fa">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*aAdY7RCEWvRPI_BZYRKQHw.png" /></figure><p>Although the resource generator provides you RESTful routes, our purpose is to only have the GET ( <em>/bands/:id</em> ) and DELETE ( <em>/bands</em> ). We can specify that with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*xrrxi8mXO-pYaRvam16ztw.png" /></figure><p>If you check the available routes again, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*v6BpxQllRByQhSyrvndoXQ.png" /></figure><p>As we will be working with 2 situations in which our controller actions (show and destroy) will have to communicate with the model to retrieve some data requested from the client, we are going to take a look at each one at a time.</p><p>We also need to seed our database table with some sample data so we can use in our example, so I have created some in the <em>db/seeds.rb</em> file:</p><pre>band1 = Band.create(name: &quot;The Beatles&quot;, members: &quot;John Lennon, Paul McCartney, George Harrison and Ringo Starr&quot;, concert_time: 10)<br>band2 = Band.create(name: &quot;U2&quot;, members: &quot;Bono, the Edge, Adam Clayton, and Larry Mullen Jr.&quot;, concert_time: 19)<br>band3 = Band.create(name: &quot;Queen&quot;, members: &quot;Freddie Mercury, Brian May and Roger Taylor, later joined by John Deacon&quot;, concert_time: 13)</pre><p>Now you can migrate the changes from the migration file created and seed them with the data above, running the following command:</p><pre>$ rails db:migrate db:seed</pre><p>For the next steps you can use your browser, the console or Postman to make requests to our rails server.</p><blockquote>Note: The controllers act as a middle man between the model and the view. Its main purpose is to gather specific data from the model and send it out to the view. In this post, we will be working only with the controller to handle exceptions, which will be explained in the next sections.</blockquote><h3>show Exception — ActiveRecord::RecordNotFound</h3><p>Let’s start creating the code for the <em>show</em> action in our <em>bands controller</em>. The show action is responsible for asking our Model to search up a specific data, given its <em>id attribute</em> from the params:</p><pre>class BandsController &lt; ApplicationController<br><br># GET /bands/:id<br>  def show<br>    band = Band.find(params[:id])<br>    render json: band, status: :ok<br>  end<br><br>end</pre><p>In the <em>show</em> action, we are applying the .<em>find</em> method in our Band model, passing the <em>params id</em> attribute from the client request as an argument. Then, we are using <em>render json: </em>so that the data found in our database should be rendered and with the status of 200 (OK).</p><p>We have now set up the controller with the show action to handle client requests. I will be working with Postman as a mocking client, but you can choose any client of your preference.</p><p>In the directory of your rails API, start the server:</p><pre>$ rails s</pre><p>If we make a GET request passing the :id of 1, we receive on the body of the response our first band:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmMy3EqlGG622vv6pKiQRA.png" /></figure><p>That was expected. Now let’s see what happens if we make a GET request to the band with id equal to 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yJoLhxerHqxYwcgUWJQlQ.png" /></figure><p>We receive an object describing an error message with the 404 status of Not Found, along with the following exception:</p><p><em>#&lt;ActiveRecord::RecordNotFound: Couldn’t find Band with ‘id’=10&gt;”</em></p><blockquote>Note: You can also check the logs of your server in your command line for the error.</blockquote><p>Well, this is a helpful error message. As we can see in Postman, we get a Ruby hash with some information, but the main piece of this object is the exception key value pair. But how are we able to get this information so we can send it back as a response to the client? We can use <strong><em>rescue </em></strong>to handle exceptions.</p><p>In our bands controller, let’s use <em>rescue</em> on the exception raised and add a <em>byebug</em> to check the value of <em>error</em>:</p><pre>class BandsController &lt; ApplicationController<br><br># GET /bands/:id<br>  def show<br>    band = Band.find(params[:id])<br>    render json: band, status: :ok<br>  rescue ActiveRecord::RecordNotFound =&gt; error<br>    byebug<br>  end<br><br>end</pre><p>You can hit the <em>byebug</em> session refreshing your webpage or resending the request in Postman. We will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*KJTuUYr2y5yM9F-LI3dc1Q.png" /></figure><p>What we get back is that <em>error</em> is an instance of <em>ActiveRecord::RecordNotFound </em>and we can even see what methods it has built-in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rsE7JMdEb7s5v1ATaF2vw.png" /></figure><p>Still in your <em>byebug</em> session, try using the <em>.message </em>method<em> </em>on the <em>error </em>instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*qER6gXvbUGeJQOdQkgOwrA.png" /></figure><p>Nice, we can now access the error message just chaining the <em>.message</em> method to the <em>error</em> instance and use its value as a response to the client, with a status of <em>not_found</em>:</p><pre>class BandsController &lt; ApplicationController<br><br># GET /bands/:id<br>  def show<br>    band = Band.find(params[:id])<br>    render json: band, status: :ok<br>  rescue ActiveRecord::RecordNotFound =&gt; error<br>    render json: { error: error.message }, status: :not_found<br>  end<br><br>end</pre><p>Let’s make the request one more time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hqCuyzOiZQWBL3NARI09A.png" /></figure><p>The response body is the error that we defined in our controller action, along with its status code 404 Not Found! Now the client can have a clean and descriptive error about the requested route.</p><h3>destroy Exception — ActiveRecord::RecordNotFound</h3><p>The <em>destroy </em>action in our bands controller can use the same process as the <em>show</em> method to rescue an exception. Let’s take a look at our <em>destroy</em> action:</p><pre>class BandsController &lt; ApplicationController<br><br>  def show<br>    band = Band.find(params[:id])<br>    render json: band, status: :ok<br>  rescue ActiveRecord::RecordNotFound =&gt; error<br>    render json: { error: error.message }, status: :not_found<br>  end<br><br>  def destroy<br>    band = Band.find(params[:id])<br>    band.destroy<br>    render json: {}, status: :no_content<br>  rescue ActiveRecord::RecordNotFound =&gt; error<br>    render json: { error: error.message }, status: :not_found<br>  end<br><br>end</pre><p>In destroy, the controller is going to also ask the model to find data in the database and if it finds, it should delete it with the .<em>destroy</em> method and render the :<em>no_content</em> status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKMt0jF6BWMHHzmaQl6mgA.png" /></figure><p>However, if it doesn’t find the object with the <em>id</em> from the params, it will raise an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saJhZCudfAWIMXjzI_RngQ.png" /></figure><p>Great. But if you noticed we are using the same code in two different actions. We can dry up our code, adding a <em>rescue_from</em> outside of the actions and create a private method to display an error message:</p><pre>class BandsController &lt; ApplicationController<br>rescue_from ActiveRecord::RecordNotFound, with: :band_not_found<br><br>  def show<br>    band = Band.find(params[:id])<br>    render json: band, status: :ok<br>  end<br><br>  def destroy<br>    band = Band.find(params[:id])<br>    band.destroy<br>    render json: {}, status: :no_content<br>  end<br><br>  private<br><br>  # Render error message if the band is not found in the database<br>  def band_not_found<br>    render json: { error: &quot;Band not found&quot; }, status: :not_found<br>  end<br><br>end</pre><p>This way, the client gets back a general message informing that the band was not found in the database. You will be able to use the <em>rescue</em> not only for the <em>show</em> and <em>destroy</em> methods, but for any other methods in the scope where the <em>rescue</em> was defined.</p><h3>Conclusion</h3><p>Using <em>rescue</em> and <em>rescue_from</em> to handle exceptions are great ways to add some<em> Active Record</em> magic to the code in your controller. Instead of using an<em> if else</em> statements here (you could do it using <em>find_by)</em>, which would also work, we handled exceptions without using the explicit logic behind one of the most common errors: a requested resource that cannot be found.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbae5aa79cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails Generators]]></title>
            <link>https://medium.com/@brasildu/ruby-on-rails-generators-a747212177fa?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/a747212177fa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 06:41:58 GMT</pubDate>
            <atom:updated>2022-12-31T06:41:58.301Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Ruby on Rails backend API from scratch using boilerplate code can be a very hard task. If you are familiar with Ruby language used with the Rails gem to simplify the creation of backend API servers, in this post I will be unpacking one of Rails most powerful tools for that purpose: <strong>generators</strong>.</p><p>Creating a Rails API through the command line interface ($ <em>rails new rails_application_name</em>) is already a great tool itself, which sets up various backend files and directories, giving them a pre-built code and establishing name conventions.</p><h3>Rails application set up</h3><p>If you don’t have Rails yet, you can do it using the following command available with RubyGems:</p><pre>$ gem install rails</pre><p>Still in your command line, you can check for your current rails version:</p><pre>$ rails -v<br>Rails 7.0.4</pre><p>Great. Having rails ready, let’s start by configuring and generating the most essential files for a RESTful API that in the future will be able to receive code that responds to CRUD client requests made with HTTP verbs:</p><ul><li><strong>C</strong>reate → POST HTTP request;</li><li><strong>R</strong>ead → GET HTTP request;</li><li><strong>U</strong>pdate → PATCH/PUT request;</li><li><strong>D</strong>elete → DELETE request</li></ul><p>Configuring your API properly using built-in Rails tools that choose convention over configuration, will save you a lot of time when debugging, preventing errors.</p><p>For this post I am going to use a practical example of an API: a server that contains data of a flowers store.</p><p>However, we won’t be writing all of the code by scratch to map between routes, controllers and models. We will simply be using a <strong>generator </strong>to create all the functionality and association that we need.</p><p>First, we are going to create our rails application through the command line:</p><pre>$ rails new flower-store</pre><p>Then, navigate to the flower-store directory.</p><h3>Rails generators</h3><p>Before hopping into our flower store example, which we will be creating with the <strong>resource</strong> generator in the end of this post, let’s go over some examples of Rails generators. Rails itself has great helping texts on its console utilities. In the flower-store rails app directory we can run:</p><pre>$ rails --help<br># or<br>$ rails -h</pre><p>The help flag will display the most common rails commands used, along with others (not displayed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zc4HVuVsXK9I0_P5X3iucw.png" /></figure><p>We notice that the first command listed is the one we will be working with, <strong>generate</strong>.</p><p>Now, we can check what different kinds of generate options we have, running the command:</p><pre>$ rails g -h</pre><p>We will get back a list of generators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*M_d56tvIk1hK5dRKMyOH5g.png" /></figure><p>We will be covering on this post: <strong>controller</strong>, <strong>model</strong>, <strong>migration</strong> and <strong>resource</strong>.</p><h3>generate controller</h3><p>Each generator automates a specific task of creating, editing files and other helpful functionalities for setting up the Rails API. For example, if we want to create a <strong>controller </strong>for our flower-store app, we can do so:</p><pre>$ rails g controller Flowers</pre><p>We can even check how the controller command syntax works through the terminal, using once again the -h flag:</p><pre>$ rails g controller -h</pre><p>If we check the returning helper text, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*SEgIX1yOv0Ddx-k8uTirCQ.png" /></figure><p>Above, Rails is giving us the template for the generate controller command:</p><pre>$ rails generate controller name_of_controller [action]</pre><p>Rails also shows a description about the controller generator, which is very helpful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lt9FBOopqI0Emp9gLSnaKA.png" /></figure><p>Let’s use all of this information given from rails, to create a flowers controller:</p><pre>$ rails g controller Flowers</pre><blockquote>Note: Make sure that you check the helper texts to follow naming conventions when using the generators. For example, above we used upper camel cased letters on plural, but we could have also achieved the same goal with snake cased syntax.</blockquote><p>The command will create a new file called <em>flowers_controller.rb</em>, that inherits from <em>ApplicationController:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*wht5ZZiaTIcapDi5lFhdeg.png" /></figure><p>In the controllers directory, we can check where the <em>ApplicationController</em> comes from: it is a subclass of <em>ActionController::Base </em>and is located in a file already set up by Rails. This file the only one that inherits from <em>ActionController::Base</em>, which is responsible for handling client requests and performing actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tZ1baDTWv9Gsa4DRu1Deyw.png" /></figure><p>Nice, we now have our controller set up. But, what if we want to undo the command? We can simply run:</p><pre>$ rails d controller Flowers</pre><p>The ‘d’ stands for delete, so we are deleting the controller and passing its name given upon creation.</p><h3>generate model &amp; generate migration</h3><p>Now let’s try a different generator: <strong>model</strong>. As the name already says, the model generator creates a model file in its proper directory, along with a migration file:</p><pre>$ rails g model Flower</pre><p>Running the command above (notice that the model name is on singular by convention), we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*fkKwDGjy5Ad4cy8l_470vw.png" /></figure><p>We can check the logs of any generator in the console once the command in ran. In the model, we see that Active Record created a migration file in the proper db/migrate directory and also a <em>flower.rb</em> model file in app/models.</p><blockquote>Note: When we use generate, it will invoke the test_unit and create some files automatically. These are system tests that allows us to test user interactions with our application.</blockquote><p>To visualize that our files were properly created, navigate to their own directories to check each of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*386KxJdUaw4KqATjaQWmhQ.png" /><figcaption><strong>model file</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*rfcqVzG9muQd4AY2XpqPug.png" /><figcaption><strong>migration file</strong></figcaption></figure><p>Our model generator created both files and set up the <em>create_table</em> method in our migration, so we can add columns and data types to our table. We can even generate a model already passing the table columns attributes and also use a flag to specify if we don’t need the system tests to be installed:</p><pre>$ rails g model Flower name species price:integer --no-test-framework</pre><p>Above we are generating our model, giving the tables columns names that will be mapped by the model. Each table column as we know, need to have a data type defined. <strong>If we are not giving any type for the column name, it means that it’s a String by default</strong> — notice that we had to specify the price data type as it is not a String.</p><p>For the <strong>migration</strong> generator it works similarly but instead of creating both model and controller files, it will only create a migration file. Although, you can still specify the table attributes:</p><pre>$ rails g migration CreateFlowers name species price:integer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbdSzIILoPMpMZoIblaElQ.png" /></figure><p>Above we can see that it was created a new migration file with its time stamp and snake-cased name by convention. Let’s check the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*oGSY6pRnNCMsaQg3TdPHlQ.png" /></figure><p>We have successfully created our migration with the generate command, along with its table structure. Great!</p><blockquote>Note: Remember that you can always undo each generate command copying it and replacing the ‘g’ for ‘d’ of delete, so you can go trough each generator examples in this post.</blockquote><h3>generate resource</h3><p>The <strong>resource</strong> generator is the most powerful one: with only one command it generates a model, controller, migration, views directory and optionally routes.</p><p>With resource, we will be finally creating all the files for our flower store data API, with a single line! Check it below:</p><pre>$ rails g resource Flower name species price:integer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZX-pVKjIHEK76N8r3AtCTg.png" /></figure><p>Wow! Many files were created with this command. From the top line of the log generated and going down, we have created:</p><ul><li>Model and migration files;</li><li>Rails system test files;</li><li>Controller file;</li><li>Views directory and its respective file;</li><li>Route file.</li></ul><p>Next, check each of these changes in their respective directories given by the paths. Now you can start coding in your backend API some functionalities to handle client requests!</p><h3>Conclusion</h3><p>Rails gem is becoming more and more popular around developers due to its facility to create structured API backends. Along with Rails preference of convention over configuration, we don’t need to worry about setting up and memorizing all naming conventions and accidentally break our application.</p><p>With <strong>Rails generators</strong>, we are able to:</p><ul><li>Give our application commands through the command line, without going directly to a file and modifying it;</li><li>Create pre-configured files with single line commands using generators like <strong>controller</strong>, <strong>model</strong>, <strong>migration</strong> and <strong>resource</strong>;</li><li>Use the <strong>resource </strong>generator to create different API files (model, migration, controller, views, route);</li><li>Save time configuring our application;</li><li>Prevent errors and bugs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a747212177fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up different Ruby versions]]></title>
            <link>https://medium.com/@brasildu/set-up-different-ruby-versions-a40a95a03b4?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40a95a03b4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 09:04:21 GMT</pubDate>
            <atom:updated>2022-12-29T09:03:58.997Z</atom:updated>
            <content:encoded><![CDATA[<p>These days I had to work on a Ruby backend API code, which required me to run <em>bundle install </em>to install gems from the<em> Gemfile.</em> I do have Ruby on my machine (MacOS), I use the latest version 3.1.3 — at the time I wrote this post. However, I ran into an error when trying to install the dependencies with bundle for my project:</p><pre>nokogiri-1.11.3-x86_64-darwin requires ruby version &lt;<br>3.1.dev, &gt;= 2.5, which is incompatible with the current<br>version, ruby 3.1.3p185</pre><p>It’s a helpful error that I get back in my terminal, which translates to: “Hey, when you executed <em>bundle install</em>, I tried to install the <em>nokogiri</em> gem but it was not successful, as it requires a Ruby version less than 3.1.dev, but greater or equal than 2.5.”</p><p>However, this was not the first time I ran into this error message when trying to install gems for my Ruby applications. So I went to my terminal to check which ruby I was using:</p><pre>$ ruby -v<br>ruby 3.1.3p185</pre><blockquote>Note: If you ran the command above and got back /usr/bin/ruby, it means that you are using the <strong>MacOS system Ruby</strong>, which is not recommended. If you try installing gems with this Ruby, it will attempt to install them in the Ruby system directory, which ordinary users don’t have access to modify. It also raises issues related to system security and gem management.</blockquote><p>If you don’t have Ruby yet, we will be going through a step-by-step on how to install it using <a href="https://brew.sh/"><strong>Homebrew</strong></a> — a very handy package and software manager. In case you don’t have Homebrew, you can install it through their website and check about its system requirements.</p><p>Make sure you have Homebrew installed so you can follow along with the next steps.</p><h3>Chruby</h3><p>For being able to work with different versions of Ruby, we will need a version manager. There are some popular version managers available like RVM and Asdf, which provide other functionalities beyond what our goal is — switching between Ruby versions. We could also use Frum, the latest version manager for Ruby (by the time I wrote this post).</p><p>However, as we just want to change Ruby’s version throughout projects, we will be using the <strong>Chruby</strong> shell script. Chruby makes the $PATH environment variable relate to a specific Ruby version, also allowing us to easily switch between versions.</p><p>Let’s start installing <strong>ruby-install </strong>(to make it easier to install specific Ruby versions)<strong> </strong>and<strong> Chruby </strong>with<strong> </strong>Homebrew<strong>:</strong></p><pre>$ brew install ruby-install chruby</pre><p>Next, we can verify that ruby-install is now available:</p><pre>$ ruby-install -V<br>ruby-install: 0.8.5</pre><p>Then you can go to the ~/.zshrc file (hidden file created when Zshell was installed), using the command below:</p><pre>$ open -e ~/.zshrc</pre><p>The file will open in a text editor and you can add the following code:</p><pre>source /usr/local/share/chruby/chruby.sh<br>chruby ruby-3.0.5</pre><p>The first line makes the chruby command available in the terminal, while the second line we are setting up a default version of Ruby — as I am working with Ruby projects that require a specific Ruby version for some gems to run properly, I set it to ruby-3.0.5.</p><p>We can now save, close the file and reopen the terminal. Doing that, let’s check that our Chruby is ready:</p><pre>$ chruby -h<br>usage: chruby [RUBY|VERSION|system] [RUBYOPT...]</pre><h3>ruby-install</h3><p>Next we will be installing some Ruby versions so we can make sure our Chruby version manager is working properly. As we already have ruby-install, we can use it to install different Ruby versions:</p><pre>$ ruby-install 3.0.5</pre><p>Or even the latest one:</p><pre>$ ruby-install --latest ruby</pre><p>It might take some time, but once you are done installing them you can verify that the Ruby versions were successfully installed with the chruby command — make sure you quit the terminal before doing it, as we just installed Rubies:</p><pre>$ chruby<br>* ruby-3.0.5<br>ruby-3.1.3</pre><p>Above we were able to check the two Ruby versions available to us (the latest one by the time of this post is 3.1.3) and that the default (*) version is 3.0.5, which we set it up with the ~/.zshrc file previously.</p><h3>Changing Ruby version</h3><p>Now to change the current Ruby version (ruby-3.0.5) to the other available (ruby-3.1.3):</p><pre>$ chruby 3.1.3</pre><p>Checking current Ruby’s version:</p><pre>$ ruby -v<br>ruby 3.1.3</pre><p>Perfect! We just used Chruby to switch between Ruby versions. Notice that if you try running chruby with a Ruby version not installed, it show the following message:</p><pre>$ chruby 3.3.0<br>chruby: unknown Ruby: 3.3.0</pre><h3>Conclusion</h3><p>We just went through the steps on how to use different Ruby versions to match project requirements:</p><ul><li>Installed <a href="https://brew.sh/"><strong>Homebrew</strong></a> package manager;</li><li>Installed <strong>ruby-install</strong> for easily installing multiple Ruby versions;</li><li>Installed <strong>Chruby</strong> version manager.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40a95a03b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Database — Part 3 of 3: Table Data Association]]></title>
            <link>https://medium.com/@brasildu/creating-a-database-part-3-of-3-table-data-association-b7475d6de709?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7475d6de709</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 02:59:50 GMT</pubDate>
            <atom:updated>2022-12-21T02:59:50.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Database — Part 3 of 3: Table Data Association</h3><p>So far in parts 1 and 2 from the ‘<em>Creating a Database</em>’ post series, we went through:</p><ul><li>The file hierarchy composition of the project;</li><li>Functionality and usage of each file, along with name conventions and file configurations;</li><li>Created migrations for the <em>customers</em> and <em>orders</em> tables;</li><li>Created <em>orders</em> and <em>customers</em> tables structures and migrated those changes to the database;</li><li>Seeded the table rows with sample data using Active Record through the Pry console.</li></ul><p><strong>→ Project Composition:</strong></p><ul><li><a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">1st part</a>;</li><li><a href="https://medium.com/@brasildu/creating-a-database-part-2-database-tables-and-seeding-2ad2b77c2f4b">2nd part</a>;</li><li>3rd part (this post).</li></ul><p>Now we are heading to the 3rd and last part of the project. Let’s take a look again at the tables we created in the <a href="https://medium.com/@brasildu/creating-a-database-part-2-database-tables-and-seeding-2ad2b77c2f4b">last post</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*P5ZqQveqd0ENHnm-5uTrMA.png" /><figcaption><strong>customers table</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*3nF8VpBbqRksndG21yCQFg.png" /><figcaption><strong>orders table</strong></figcaption></figure><p>Above we have two tables: <em>orders</em> and <em>customers</em>. The relationship between them is represented through the <em>Entity Relationship Diagram</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0dXIbkIH8g-6-ZJC.png" /></figure><h3>Adding a foreign key column</h3><p>Knowing that the relationship of <em>customers</em> and <em>orders</em> tables is one-to-many, we can write down the following logic:</p><ul><li>A customer has many orders;</li><li>An order belongs to a customer.</li></ul><p>To create the connection between both tables, we need to use a foreign key column in the <em>orders</em> table, indicating that an order belongs to a specific customer with a foreign key corresponding to a customer’s primary key from the <em>customers</em> table.</p><blockquote>Note: It’s extremely important that once again we follow name conventions. The foreign key column we will be creating in the orders table needs to have the exact same name of the table where the primary key of a customer is located, so Active Record can recognize the connection between the tables.</blockquote><p>To modify a database table structure we cannot do it directly in the migration file, neither in <em>schema.rb</em>. The best practice if we are going to make a change is to create a migration so we can have a version control of this change. Let’s create a migration with the name flag of <em>add_customer_id</em> to indicate that we are going to add a customer id column to the orders table:</p><pre>$ bundle exec rake db:create_migration NAME=add_customer_id</pre><p>Doing so, will generate a new migration file with a timestamp and the name we just gave in the command, along with the upper camel-cased AddCustomerId class and the <em>change</em> method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8PMZj4K9ruSiUqX-JB9og.png" /></figure><p>Now we can use the<em> add_column</em> Active Record migration method to add a column to the <em>orders</em> table, specifying the table’s name, the column’s name and data type we want the column to have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCiRC_59lN8CVUxTjv2Rnw.png" /></figure><p>To perform the migration, you can execute the following command in the terminal:</p><pre>$ bundle exec rake db:migrate</pre><p>If we take a look at our <em>schema.rb</em> file, we now see that the <em>orders</em> table has a new column of <em>Integer</em> type, called <strong>customer_id:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1FRgLjhlUxaQph99t6z_Q.png" /></figure><blockquote>Note: Remember that you cannot make alterations to this file, it is just a snapshot of our database.</blockquote><p>Checking the <em>orders</em> table using the SQLite extension for Visual Studio, we have our <em>customer_id</em> column we just added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*mZjK2QxNV378WH9hd4ILwg.png" /></figure><p>Through a pry session, let’s give the orders some <em>customer_id</em> foreign keys. You can initialize the console with the command below:</p><pre>$ bundle exec rake console</pre><p>To assign a foreign key of a customer to an order, let’s first retrieve the customers that we have in the <em>customers</em> database table, using the <em>.all Active Record </em>method on our <em>Customer</em> class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vU8Dxh5YlzgsnH-b5-7YMw.png" /></figure><p>We can use the two customers primary keys to be the foreign keys in the <em>orders</em> table. First, let’s assign the order with <em>id = 1</em>, a <em>customer_id</em> of the second customer from the <em>customers</em> table:</p><pre># Save the first order from the orders table into a variable<br>order_one = Order.first<br><br># Save the customer with id=2 from the customers table into a variable<br>second_customer = Customer.find(2)<br><br># Save the id of the retrieved customer into a variable<br>second_customer_id = second_customer.id<br><br># Use the .update method to update the first order&#39;s customer_id<br>order_one.update(customer_id: second_customer_id)</pre><p>You can see below how it looks on the pry session in the terminal, which also logs the SQL code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V76kViEEec0YIO8BxgaAuw.png" /></figure><p>Now let’s repeat the process but now assigning the order with <em>id = 2</em>, a <em>customer_id</em> of the first customer from the <em>customers</em> table:</p><pre># Save the second order from the orders table into a variable<br>order_two = Order.first<br><br># Save the customer with id=1 from the customers table into a variable<br>first_customer = Customer.find(1)<br><br># Save the id of the retrieved customer into a variable<br>first_customer_id = first_customer.id<br><br># Use the .update method to update the second order&#39;s customer_id<br>order_two.update(customer_id: first_customer_id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZg3h_J6SEAtjBcvk9vjsg.png" /></figure><p>Nice! Now our <em>orders</em> table has its <em>customer_id</em> column with values related to customers present in the <em>customers</em> table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*y0k-K5ccbOS3djsvlMHahQ.png" /></figure><p>We just went through the steps for updating a column’s data. We didn’t need to do all of that, but it’s important to have an understanding of where the foreign keys from the <em>customer_id </em>column come from — we could have just directly updated each order to have a customer id of values 2 and 1, without going through the process of getting it from a customer in the <em>customers</em> table.</p><p>I ended up adding more data to the tables so we will be going into the next section with the following updated tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*qCGIWRXAQyplZYiJQYnHbA.png" /><figcaption><strong>customers table</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*M04fCMD1OF0N-tlp7khvQg.png" /><figcaption><strong>orders table</strong></figcaption></figure><h3>Active Record Macros</h3><p>So far we have the <em>customer_id </em>column in the <em>orders</em> table representing an association with a <em>customer</em> through a foreign key, but we still need to take an important step to make the connection work.</p><p>To do so, we are going to use Active Record macros which are methods that give our application some features to establish relationships between models. For example, we have a macro called <em>attr_accessor</em> from Active Record that allows you to both read and change data of an Object.</p><p>The macros we will be using to establish the logic between the customers and orders tables are:</p><ul><li>has_many</li><li>belongs_to</li></ul><p>Going to our<em> customer.rb</em> and <em>order.rb</em> models, we currently have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PR_sV7BevMU4qh-6LdxiLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYR3ArInfn2ndR11wE7WHw.png" /></figure><blockquote>Note: It’s essential to include the class inheritance from ActiveRecord::Base as it is where the macros come from.</blockquote><p>Let’s add the has_many macro (or method) to the Customer class, to indicate that a customer has many orders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0qTq6wbcX9sj29XJp-5Og.png" /></figure><p>Now in the order.rb file, we are going to use the belongs_to to indicate that an order belongs to a customer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74hSOGjnTe0I-KJ33jpcaQ.png" /></figure><p>The macros we added to the classes above are nothing more than a Ruby method that takes a symbol as an argument. For the one-to-many relationship to work, we need to make sure we follow a name convention: the <em>belongs_to</em> macro should take a symbol argument on singular (<em>:customer</em>) and the <em>has_many </em>macro, on plural (:<em>orders</em>).</p><p>This makes sense if we think of the one-to-many association of the <em>orders</em> and <em>customers</em> tables: we have one customer that has many orders, being the orders belonging to a single customer, but the opposite is not true — an order cannot have many customers.</p><h3>Manipulating data with Associations</h3><p>Now that we added a column for the foreign key of a customer in the <em>orders</em> table and established a relationship between the classes of <em>Order</em> and <em>Customer</em> through Active Record macros, we can start working with our association. First, run the <em>console</em> Rake task from your terminal, it will start a pry session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*vqHcg0RPZo9ZOzfoXBON-g.png" /></figure><p>Adding the <em>has_many</em> macro to the <em>Customer</em> class, generated the .<em>orders</em> instance methods, which we can use to retrieve the orders from a particular customer:</p><pre># Get the first customer<br>customer_one = Customer.first<br><br># Retrieve the orders from the customer with the .orders method<br>customer_one.orders</pre><p>You can check how it looks in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5kmlmmSB8JrObM4lrdmHA.png" /></figure><p>Great! We were just able to access the orders from a customer just chaining the .<em>orders </em>method directly to a customer. Let’s repeat the process for the other customers:</p><ul><li><strong>Retrieving orders from a customer of id=2</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWANkudIwO8zQw43m7tLCw.png" /></figure><ul><li><strong>Retrieving orders from a customer with id=3</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dV7-0hNKB8_wk9U8NardTQ.png" /></figure><p>Now looking at the <em>Order</em> class, we have the <em>belongs_to</em> macro that adds some additional functionality to our class. This is how we would create a new <em>Order</em> instance before we had the <em>belongs_to:</em></p><pre>customer = Customer.first<br><br>order = Order.create(number: 7, delivered: false, item_name: &quot;king bed&quot;, customer_id: customer.id)</pre><p>With the macro added to our <em>Order </em>class, we can assign a <em>customer_id </em>foreign key passing the instance of a customer directly, instead of getting a customer id:</p><pre>customer = Customer.first<br><br>order = Order.create(number: 8, delivered: true, item_name: &quot;chairs set&quot;, customer: customer)</pre><p>Another useful tool from the <em>belongs_to</em> macro is that we are able to use a <em>create_customer</em> method, which creates a customer adding it to the <em>customers </em>table and then we can associate the method with an order directly:</p><pre># Create an order without assigning a foreign key<br>order = Order.create(number: 9, delivered: false, item_name: &quot;center table&quot;)<br><br># Associate the order with a new customer created through the .<em>create_customer</em> method<br>order.create_customer(name: &quot;Meghan Sefried&quot;, address: &quot;40 Warner Ave, CA&quot;, city: &quot;Los Angeles&quot;, zip: 30597)<br><br># Save the association<br>order.save</pre><p>For the has_many macro we can also perform some helpful methods. One common case is to use the &lt;&lt; method (shovel method) to add a new order to a customer:</p><pre>customer = Customer.last<br><br>customer.orders &lt;&lt; Order.new(number: 10, delivered: true, item_name: &quot;mirror&quot;)</pre><p>So handy! It’s not just easy to use but it’s also easy to understand what we are doing in our code.</p><h3>Conclusion</h3><p>This was the last part of the<em> ‘Creating a Database’ </em>post series. In this post we:</p><ul><li>Added a foreign key column to our orders table, to associate an order with a customer;</li><li>Created the association between a customer and an order, adding foreign key values to the <em>customer_id</em> column;</li><li>Added the <em>belongs_to</em> and <em>has_many</em> macros to the Order and Customer classes respectively;</li><li>Went through some examples of how the macros can create helpful methods to associate two tables.</li></ul><p>Building associations between models with macros allows access to more methods and therefore it expands our application. The <em>‘Creating a Database’ </em>project had 2 tables in a <em>one-to-many</em> table association. However, you can develop database table associations using several tables interconnected, for example with a <a href="https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association"><strong><em>many-to-many </em></strong></a>relationship, applying the <em>has_many :through </em>macro<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7475d6de709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Database — Part 2: Database tables and seeding]]></title>
            <link>https://medium.com/@brasildu/creating-a-database-part-2-database-tables-and-seeding-2ad2b77c2f4b?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad2b77c2f4b</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 22:41:15 GMT</pubDate>
            <atom:updated>2022-12-21T03:01:26.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Database — Part 2 of 3: Database tables and seeding</h3><p>In the <a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">first part</a> of this post, we went over the file hierarchy composition of the ‘C<em>reating a Database</em>’ project, describing how each file contributes for the backend development and their configuration importance.</p><p><strong>→ Project Composition:</strong></p><ul><li><a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">1st part</a>;</li><li>2nd part (this post);</li><li><a href="https://medium.com/@brasildu/creating-a-database-part-3-of-3-table-data-association-b7475d6de709">3rd part</a>.</li></ul><p>Now in part 2 we will be actually making use of what we have already created in part 1 to migrate, build and seed the database. If you didn’t have a chance to read part 1, you can find it <a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">here</a>.</p><p>Let’s check again how our project structure currently looks like, after going through the steps in part 1 of creating each file and their configuration, organizing them into directories representing a file hierarchy tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*5acecHukqwi-5A4M.png" /></figure><p>We also saw the one-to-many table association that we have for the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kvcA2ZZN7gBmhRC6.png" /></figure><ul><li>Customers → Has many orders;</li><li>Order → Belongs to a customer.</li></ul><p>Now that we have our files set up a visualization of our database, let’s create it! We will be using Ruby OO language to perform interactions, SQLite database engine, methods and tasks from very handy gems like Active Record and Rake — if you are curious about them, you can check the first part of this post at ‘<a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">Creating a Database — Part 1: File structure</a>’.</p><p>You can follow along with the sections below, that describe a step-by-step of creating the database, seeding and interacting with it.</p><h3>Creating tables</h3><p>In the first part of the project, we performed two important steps for creating the database tables:</p><ul><li>We created a migration to represent the creation of the <strong>customers</strong> and <strong>orders</strong> tables, running the following commands in the terminal:</li></ul><pre>$ bundle exec rake db:create_migration NAME=create_customers</pre><pre>$ bundle exec rake db:create_migration NAME=create_orders</pre><p>Executing the commands, generated two migrations version controls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*8PeDYT3cOsXkh7ArXlgUXA.png" /></figure><p>The files have a timestamp indicating the date and time in which the migrations were created.</p><p>Taking a look at the files that represent the migration for creating the <strong>customers </strong>and<strong> orders </strong>tables, we can notice that some code was automatically generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wT4C27Fw1MVfuoxnsmvX5g.png" /><figcaption><strong>create_customers migration</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJFW2r9Ntj5v3IEICXMmWg.png" /><figcaption><strong>create_orders migration</strong></figcaption></figure><p>We have a class of CreateCustomers and CreateOrders that correspond to the exact same snaked case name of when we created these migrations with<em> NAME=create_customers </em>and<em> NAME=create_orders</em>, but now upper camel cased.</p><blockquote>Note: This is a very important convention to follow as if the migration file name and the class name are different from each other, you will run into a <strong>NameErro</strong><em>r</em>.</blockquote><p>Both classes are inheriting from the <strong>ActiveRecord::Migration</strong> module from when we executed the migrations. It also auto generated a <strong>change</strong> method which is the most common for creating tables. In the block of this method, we will be creating the customers and orders tables structures respectively, with the<em> create_table</em> method and giving them columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGeYWRANxwdWtPynJx2LWg.png" /><figcaption><strong>create_customers migration</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6xtu6at3m8hk4imk8Wnpg.png" /><figcaption><strong>create_orders migration</strong></figcaption></figure><p>Above, we created the <strong>customers</strong> and <strong>orders </strong>tables following the name convention that the table is the plural of its corresponding class, in this case the Customer and Order classes from the Ruby model files below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*-3ABXwUh1ZiN1vR4Ah7SjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*8QmAXTPSbzuDwjE06HFTcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*VmE8nZckcmz3qAywS0es2Q.png" /></figure><p>Back with the migrations, we specified the data type of each column and the column’s names<em>. </em>On line 4 from the create_customers migration file for example, <em>t.string</em> represents a method for creating a column of String datatype and the symbol right next to it is the method argument, representing the name of the column, in this case “name”.</p><p>But writing that structure in the migration files still doesn’t create the tables we want. To do so, we need to migrate those changes through the terminal, running the following command:</p><pre>$ bundle exec rake db:migrate</pre><p>Doing that, Active Record creates a new file inside the migrate directory, called <em>schema.rb:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7K-dlRKaTypJYCksrUkVA.png" /></figure><p>The file above is auto-generated from the current state of the database and you should <strong>NOT</strong> edit it, as it’s just a mirror of how our database currently looks. Making changes to the database will automatically change the schema with its current version control date and time.</p><blockquote>Note: If you’re working with Visual Studio code, make sure you have installed the SQLite extension so you can visualize the database while you’re developing it. You can browser and install the extension below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*b_J_MQrZZN-XpabZYwVpJQ.png" /><figcaption><strong>SQLite extension for Visual Studio</strong></figcaption></figure><p>In the db/migrate file, if you right click on ‘<em>development.sqlite3</em>’ and then <em>‘open database</em>’, a new tab called SQLITE EXPLORER will be displayed. Clicking on it, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*vrKRK74_svejvJvRd9N51g.png" /></figure><p>You can notice that our last migration command created the two database tables of customers and orders, along with the columns names and types we specified.</p><p>We have also the <em>schema_migrations, </em>that shows us the version controls corresponding to the migrations created in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*74XGpe0F_I60NwzY8UhcbQ.png" /></figure><p>Notice that the version timestamps are the same ones from our migration files.</p><p>Now we have our tables’ structure all set up and ready to receive data, so we can interact with them retrieving, sending and updating information.</p><h3>Seeding tables</h3><p>The next step we will go through is generating data to the tables we just created. After all, what is a database without data, right?</p><p>With the Active Record gem installed and required in our<em> config/environment.rb </em>file, we can use the <strong>pry console</strong> Rake task to add some data to the tables. To start the pry console, run the command in the terminal:</p><pre>$ bundle exec rake console</pre><p>This will start a pry session. You can check that the Customer and Order classes exist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtxCYw5zKcMWju5fDMeRxQ.png" /></figure><p>As an <em>Object Relational Mapper</em>, Active Record is mapping the customers and orders tables. Using built-in Active Record methods, we can check up the columns names of the tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OQCTiUfG7IGY8s9IKTHKw.png" /></figure><p>Great! We now visualize what kind of attributes we are going to give to both a customer and an order.</p><p>To create an instance of a class, we will be using the <em>.create</em> built-in Active Record method, which will automatically save the data to the table. Let’s create a <em>customer</em> and an <em>order</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGGzZMISF2zqlMdRP9_Mcw.png" /></figure><p>On lines [2] and [3] of pry, we are creating instances of a customer and an order, respectively. Upon the creation we also assigned values of a <em>name</em> attribute for the customer and a <em>number</em> for the order, saving the instances into variables. Let’s check how our customers and orders tables currently look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*X0N5rjZpDK6cashFRRlKUg.png" /><figcaption><strong>customers table</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*0OWX55V2WO5_6vmGUsVwaA.png" /><figcaption><strong>orders table</strong></figcaption></figure><p>If you noticed the other attributes are <em>NULL</em> as we didn’t assign any values yet. We can still do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJJtFcdlTNUlf7ntUnze3w.png" /></figure><p>Even though we don’t have an <em>attr_accessor macro</em> that defines the method of assigning a value to an instance attribute, Active Record does the job for us, including the method without us needing to write down the macro.</p><p>Using the <em>c1 </em>variable created to store the customer instance, we are assigning values to the rest of the customer attributes and performing the <em>.save</em> method to save the changes to the database. Reloading the <em>customers</em> table, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*LfWnR63s6ccubSn94Qt2qA.png" /></figure><p>Now, let’s do the same for an <em>order</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wxly2PgdqorCS3uNz5i_aQ.png" /></figure><p>Reloading the orders table through SQLite Explorer, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*oPwTKzuoeXQyFZZRRcakAw.png" /></figure><p>Looking great. Now you can repeat the process to generate more data if you would like to. You can also check <a href="https://medium.com/@brasildu/seeding-sample-data-in-ruby-with-faker-gem-f383a069b922">this post</a> I made about generating sample data for tables using the Faker gem, which is very helpful.</p><h3>Conclusion</h3><p>This post was the second part of the <em>Creating a Database</em> project, consisting of 3 parts. In the <a href="https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93">1st part</a> we went through the file structure, configuring and setting up the development environment along with the database connection.</p><p>In this part 2 of 3 we:</p><ul><li>Created migrations for the <em>customers</em> and <em>orders</em> tables;</li><li>Created <em>orders</em> and <em>customers</em> tables and migrated those changes to the database;</li><li>Seeded the table rows with sample data using Active Record through the Pry console.</li></ul><p>In the 3rd and final part of this project, we will be making the tables association and then use Active Record built-in methods to retrieve, send and manipulate data from the tables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad2b77c2f4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Database — Part 1: File structure]]></title>
            <link>https://medium.com/@brasildu/creating-a-database-part-1-file-structure-92a247d01e93?source=rss-772a25b2a395------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a247d01e93</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Maria Coitinho]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 07:46:21 GMT</pubDate>
            <atom:updated>2022-12-21T03:01:15.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Database — Part 1 of 3: File structure</h3><p>When you want to create a database with tables and information that you can retrieve and manipulate through code, you need to first set up files, gems and configurations in order to make your database working and well structured.</p><p><strong>→ Project Composition:</strong></p><ul><li>1st part (this post);</li><li><a href="https://medium.com/@brasildu/creating-a-database-part-2-database-tables-and-seeding-2ad2b77c2f4b">2nd part</a>;</li><li><a href="https://medium.com/@brasildu/creating-a-database-part-3-of-3-table-data-association-b7475d6de709">3rd part</a>.</li></ul><p>This post is the 1st out of 3 parts of a project on how to create a database that has 2 tables in a one-to-many association. In this 1st part we will cover the file hierarchy composition and explain the functionality of each file of our database project, installing gems and configuring the development environment. In the <a href="https://medium.com/@brasildu/creating-a-database-part-2-database-tables-and-seeding-2ad2b77c2f4b">2nd part</a> of the ‘<em>Creating a Database</em>’ project we will be creating migrations, tables and seeding those tables. In the 3rd part, we will establish the tables connection and interact with them through Active Record built in methods and tables relationship.</p><p>Following along the steps from each section below is extremely important to have your database up and running without breaking, so we can — in the 2nd and 3rd part s— start making use of it.</p><p>The database engine I will be working with is <strong>SQLite</strong> and for our communication with the database I will be using the <strong>Ruby </strong>Object Oriented programming language.</p><h3>Introduction</h3><p>In this project we will be creating 2 tables with a one-to-many association:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vla_MX3iHrAeLOmUblC2hA.png" /></figure><p>Above we can see the relationship between customers and orders:</p><ul><li>A customer has many orders;</li><li>An order belongs to a customer.</li></ul><p>First we need to create the files for our database project’s main directory. In the end our file hierarchy should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*1UW6PROUzE2sqUD0ZPdHfg.png" /></figure><p>In the next sections I will go over the project’s files and summarize what each one of them represents.</p><h3>Gemfile</h3><p>This file contains the list of all gem dependencies required for our code written with Ruby — the code to manipulate our data — to work and should be located in the project directory root.</p><p>In the first line of the Gemfile, we need to specify the source of the gems which needs to be a valid RubyGems source. Most of the time it will be the URL “https://rubygems.org”.</p><p>The next step is to list all the required gems. Along with Ruby, these gems will enable access to libraries and programs, adding more functionality and improving our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvn7mvgDFnonHCYKDChFRA.png" /></figure><p>Let’s go through each one of them:</p><ul><li>pry → we will be using ‘pry’ with Ruby for debugging, looking up values and params.. it’s a pretty useful tool;</li><li>require_all → used to run all Ruby code from a specified directory — in our case we will be requiring all the Ruby code from the “app” directory as you will see later on this post;</li><li>activerecord → gem that installs the Active Record library used for mapping created objects in Ruby into tables in our database — the number next to the gem’s name indicates its version;</li><li>sinatra-activerecord → used to run our Rake tasks from our Rakefile;</li><li>sqlite3 → used along with SQLite engine — you must have it already installed — to interface with the SQLite database;</li><li>rake → installs Rake which allows us to build tasks in a Rakefile.</li></ul><blockquote>Note: In order to install all the gems above, you need to run the following command in your terminal:</blockquote><blockquote>$ bundle install</blockquote><h3>Rakefile</h3><p>A Rakefile is written in Ruby syntax and its main purpose is to create Rake tasks. In this project, Rake is used with <em>sinatra-activerecord gem</em> (required on line 2 below) to create migrations, check migration status, seed the database, rollback and other handful tasks for our database structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvQJyGwqOhQ0taHaPmyMwA.png" /></figure><p>On line 1 we are requiring our configuration file which I will go over it later in this post. <em>Rake</em> will also be used to start a pry session to lookup code, variable values and for debugging — this task is defined from line 4.</p><blockquote>Note: If you don’t want to see the SQL logged in the terminal, you can comment out line 6. Also to check all rake tasks available, run in your terminal:</blockquote><blockquote>$ bundle exec rake -T.</blockquote><h3>app/models</h3><p>The ‘app’ directory has a subdirectory ‘models’ which contains the Ruby files that will be created to map the database tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ccDR41sRIAxnMjJy7-gB8A.png" /></figure><p>Each file represents the class of a table that we will be mapping. Let’s first create our classes and inherit them from <em>ActiveRecord::Base </em>so we can make use of Active Record’s built-in methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxaY5vkGnDuXleIMHyoksQ.png" /></figure><p>Notice that the files have the same name as their respective classes and that they are lowercased. This is because we are following Ruby and Active Record name conventions so our program doesn’t break. It’s very important to stick to these conventions throughout our project.</p><h3>config</h3><p>The config directory is responsible for our project configuration, for example to require files and connect Ruby to the database. Let’s go over each one of its subdirectories:</p><h4>database.yml</h4><p>File where we specify the information regarding the database. For example, in our project we will be using the SQLite database as the adapter in a development environment — we can also specify here other environments like test and production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlThNTw-1iyid7YZWzdtzw.png" /></figure><h4>environment.rb</h4><p>This is our project environment file, where we are going to be requiring all files and gems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rh84aEjWthK4lUvyG-fCw.png" /></figure><p>On lines 1 and 2 above, we are requiring all the gems from Gemfile. On line 4, we are requiring our Ruby models from the ‘app’ top level directory, which has ‘models’ as a subdirectory — already mentioned earlier in this post.</p><h3>db</h3><p>The ‘db’ directory represents the database files and has a ‘migrate’ subdirectory which contains the migration files. The migrations represent a version control of the alterations made on the database structure.</p><p>Once we have a migration to represent for example the creation of a customers table, the migration file will be displayed inside the ‘migrate’ directory. Let’s go over on how that happens:</p><ul><li><strong>1st</strong> → we have an empty ‘migrate’ directory (subdirectory of ‘db’, located on the top level directory);</li><li><strong>2nd</strong> → we create a migration running the following Rake task:<em> $ bundle exec rake db:create_migration NAME = name_of_migration</em>;</li><li><strong>3rd →</strong> after running the Rake task, a file with date and time stamps is created inside the ‘migrate’ directory, representing the migration just created:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*FkZt2fJkq2wfSzPU-GNR_Q.png" /></figure><p>The name syntax of the migration files corresponds to:</p><ul><li>year/month/day/hours/minutes/seconds.</li></ul><p>This way, using migrations with Rake allows developers to have a database version control with a timeline since it was created and all of the database structure’s changes.</p><h3>Conclusion</h3><p>Building a database requires many important steps like creating files, configurations and name conventions in order to make a database working smoothly. In this post it was covered:</p><ul><li>The one-to-many table association that will be created in the part 2 of this database project;</li><li>File hierarchy composition of the project;</li><li>Functionality and usage of each file, along with conventions and file requirements.</li></ul><p>Going through all these first steps to set up the database project might not catch your eye at first, as we are not making use of the database yet. However, they are essential to make sure that the project is in good form to receive commands — in parts 2 and 3— and interact with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a247d01e93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>