<?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 Shahana Shanmugaraja on Medium]]></title>
        <description><![CDATA[Stories by Shahana Shanmugaraja on Medium]]></description>
        <link>https://medium.com/@shahanashanmugaraja20?source=rss-e43999e74116------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gFI_MCQ8i2_iZXL1AbsrFg.jpeg</url>
            <title>Stories by Shahana Shanmugaraja on Medium</title>
            <link>https://medium.com/@shahanashanmugaraja20?source=rss-e43999e74116------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:39:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shahanashanmugaraja20/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[How Fast is Fast Enough? Understanding Time Complexity]]></title>
            <link>https://medium.com/@shahanashanmugaraja20/how-fast-is-fast-enough-understanding-time-complexity-45a22cc6b86d?source=rss-e43999e74116------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a22cc6b86d</guid>
            <category><![CDATA[time-compl]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <dc:creator><![CDATA[Shahana Shanmugaraja]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 05:31:26 GMT</pubDate>
            <atom:updated>2025-04-29T05:31:26.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s be honest — “O(n log n)” and “Big O notation” sound more puzzling than everyday concepts. But if you’re learning to code or prepping for interviews, time complexity is the real MVP. What if I told you these ideas can be as simple as calling out names in a roll call? In this blog, we’ll break down time complexity using everyday analogies — no jargon, just clarity.</p><h4><strong>Time Complexity</strong></h4><p>The amount of time an algorithm takes to run, based on the size of the input. It shows <strong>how fast</strong> your code runs.</p><h4>Asymptotic Notation</h4><p>Asymptotic notation is a mathematical way to describe the efficiency of an algorithm as the input size approaches infinity. It provides a way to express the <strong>growth rate</strong> of an algorithm’s <strong>runtime</strong> or <strong>space requirement</strong>.</p><p>Rather than measuring exact steps or time in seconds, we use it to express how the number of operations <strong>scales</strong> — especially when n → ∞.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*OWTSYtgwOrKSyhgFPZX0dg.png" /></figure><blockquote><strong>Types of Asymptotic Notation</strong></blockquote><p><strong>1)Big O Notation (Upper Bound) — O(f(n))</strong></p><p>Big O gives the <strong>maximum time</strong> an algorithm can take to run, it tells us the <strong>worst-case scenario</strong>. It is often used in <strong>technical documentation</strong> to describe performance guarantees.</p><p><strong>2)Omega Notation (Lower Bound)— Ω(f(n))</strong></p><p>Omega notation gives the <strong>minimum time</strong> an algorithm will take, <strong>the best-case scenario. </strong>This notation is useful to understand how <strong>efficient</strong> an algorithm can be under <strong>ideal</strong> conditions.</p><p><strong>3)Theta Notation (Tight Bound)— Θ(f(n))</strong></p><p>Theta notation tells us that the algorithm’s running time is always around f(n), both in the best and worst cases. It is ideal for describing algorithms that perform <strong>consistently</strong> no matter the input.</p><h4>For Example,</h4><p>Imagine you’re looking for a specific book in a library with <strong>n</strong> books arranged randomly on shelves.</p><ul><li><strong>Ω(n) — Best Case (Omega)</strong><br>You spot the book <strong>on the first shelf</strong> you check.<br><strong>Best-case time</strong>: you get lucky and find it immediately.</li><li><strong>O(n) — Worst Case (Big O)</strong><br>The book is on the <strong>last shelf</strong>, or it’s <strong>not even there</strong>.<br><strong>Worst-case time</strong>: you have to check <strong>every single shelf</strong>.</li><li><strong>Θ(n) — Average Case(Theta)</strong><br>On average, the book is somewhere <strong>in the middle</strong> — not too early, not too late.<br><strong>Consistent behavior</strong>: you check around <strong>half the shelves</strong>, every time.</li></ul><h4>Why Big O Notation is the Most Widely Used ?</h4><p>Now that we know different types of notation, you might wonder — why does everyone keep talking about Big O in particular?</p><ul><li><strong>Big O</strong> gives an upper limit, helping to prepare for the <strong>worst situations</strong>.</li><li>Knowing the <strong>maximum time or resources</strong> an algorithm might consume ensures that applications remain <strong>responsive and scalable</strong>, even when unexpected or large inputs arrive.</li><li>Big O notation is favored because it provides a safe, practical, and universally accepted way to measure and discuss algorithm efficiency <strong>under any circumstance.</strong></li></ul><h4>Common time complexities</h4><ul><li><strong>O(1) — Constant time</strong></li></ul><p>The operation takes the same time no matter how big the input is. For example, you reach into a jar and take the cookie on top — no digging, <strong>always one move</strong>.</p><pre>int[] array = {1, 2, 3, 4, 5};<br>int element = array[0]; //O(1) complexity</pre><ul><li><strong>O(n) — Linear Time</strong></li></ul><p>Here, the time grows proportionally with respect to <strong>input size</strong> like reading every name on your class attendance sheet.</p><pre>int n = array.length;<br>for(int i = 0; i &lt; n; i++) {        <br>  System.out.println(array[i]);<br>} <br>//Loop runs &quot;n&quot; times                            </pre><ul><li><strong>O(log n) — Logarithmic Time</strong></li></ul><p>Imagine you’re trying to find a person’s name in a huge telephone directory. Instead of flipping page by page, you open the directory roughly in the middle. If the name is earlier in the alphabet, you only need to look in the first half. If it’s later, you focus on the second half. With each step, you cut the number of pages you need to check in half.</p><p>An operation runs in <strong>logarithmic</strong> time if it reduces the problem size by a <strong>constant factor</strong> at each step.</p><pre>for (int i = 1; i &lt; 100; i *= 2) {<br>   System.out.println(i);<br>} // This runs ~ log₂(n) times</pre><ul><li><strong>O(n log n) — Linearithmic Time</strong></li></ul><p>It combines the behavior of <strong>linear</strong> and <strong>logarithmic</strong> time complexities. you perform <strong>log n</strong> steps, and each step involves <strong>n</strong> work (or vice versa). This time complexity commonly appears in divide and conquer algorithms such as <strong>Merge sort</strong>.</p><p>Say you have 100 books to sort. Instead of sorting all at once, you split them into two halves, then into quarters, and so on — like breaking the task into levels (log n). At each level, every book is still handled once (n).<br>So while you cut down the sorting levels, you still process all the books at every level.</p><pre>for (int i = 1; i &lt;= n; i++) {<br>    for (int j = 1; j &lt; n; j *= 2) {<br>        System.out.println(j);<br>    }<br>} //Inner loop runs O(log n) for every outer loop iteration (n times), hence O(n log n)</pre><h4>Other Time Complexities You Might Encounter:</h4><ul><li><strong>O(√n)</strong> — Square Root Time</li><li><strong>O(n²)</strong> — Quadratic Time</li><li><strong>O(n³)</strong> — Cubic Time</li><li><strong>O(2ⁿ)</strong> — Exponential Time</li><li><strong>O(n!)</strong> — Factorial Time</li></ul><p>Each of these shows up in different types of problems — sorting, searching, optimization, and more.</p><p>🧠 <strong>Your Turn!</strong><br> Pick any one of these and drop a comment below explaining what you think it means — even a simple example is perfect! <br>Let’s learn together!</p><h4>How to Find Time Complexity in a Given Problem</h4><p>When you’re solving a problem, knowing how to analyze the time complexity is crucial for understanding how efficient your solution is.</p><p><strong>1)Identify the Loops</strong></p><p>Loops are the most common contributors to time complexity. The number of times a loop runs will directly impact the overall time complexity.</p><ul><li><strong>Single Loop</strong>:<br> For a simple loop running from 1 to n, the time complexity is <strong>O(n)</strong>.</li></ul><pre>for (int i = 0; i &lt; n; i++) {<br>    System.out.println(&quot;Hello world&quot;);<br>}</pre><ul><li><strong>Nested Loops</strong>:<br> If you have nested loops, multiply the complexities. For example, two nested loops each running n times result in <strong>O(n²)</strong>.</li></ul><pre>for (int i = 0; i &lt; n; i++) {<br>    for (int j = 0; j &lt; n; j++) {<br>        System.out.println(&quot;Hello world&quot;);<br>    }<br>}</pre><p><strong>2)Examine Recursion</strong></p><p>Recursive functions can have time complexities that are tricky to figure out, but they often follow a <strong>divide-and-conquer</strong> pattern. The easiest way to analyze a recursive algorithm is to set up a <strong>recurrence relation</strong>.</p><ul><li><strong>Divide and Conquer</strong>:<br>Consider an algorithm that divides the problem into two subproblems, each of size <strong>n / 2</strong>. The recurrence relation would be something like : <strong>T(n) = 2T(n / 2) + O(n)</strong></li></ul><p>Solving this recurrence relation can give us the time complexity. In this case, the solution would be <strong>O(n log n)</strong>.</p><p><strong>3)Consider Conditional Statements</strong></p><p>If your algorithm has conditional statements (like if or switch), analyze the complexity of each branch. The overall time complexity will be the <strong>maximum</strong> of the time complexities of the different branches.</p><pre>if (n &lt; 100) {<br>    System.out.println(&quot;Hello World&quot;); //O(1)<br>} <br>else {<br>    for(int i = 0; i &lt; n; i++) {<br>      System.out.println(i);<br>    }  //O(n)<br>}</pre><p>In this example, the time complexity would be <strong>O(n)</strong> since the worst case is the second branch.</p><p><strong>4)Look for Operations on Data Structures</strong></p><p>When evaluating time complexity, the type of data structure and the operations you’re performing on it play a crucial role.</p><p>For example, in arrays</p><ul><li>Accessing an element: <strong>O(1)</strong></li><li>Searching (linear search): <strong>O(n)</strong></li><li>Searching (binary search, sorted): <strong>O(log n)</strong></li></ul><p><strong>5)Simplify Using Big O Notation</strong></p><p>After you’ve examined the loops, recursion, and operations, <strong>simplify the expression</strong> using Big O notation. For example:</p><ul><li><strong>O(2n)</strong> simplifies to <strong>O(n)</strong></li><li><strong>O(n + log n)</strong> simplifies to <strong>O(n)</strong> because <strong>n</strong> dominates <strong>log n</strong></li></ul><h4>Time Complexity Cheatsheet</h4><p>For a quick, at-a-glance reference to all the common time complexities — and more — check out the <a href="https://www.bigocheatsheet.com/">Big O Cheat Sheet</a>.</p><p><em>Remember, time complexity isn’t about knowing the exact runtime but understanding how an algorithm behaves as the input grows. With practice, you’ll get better at recognizing patterns and choosing the right algorithm for the problem, making your code faster, more scalable, and ready for real-world challenges. Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a22cc6b86d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CAPTCHA Prevents Fake IPL Ticket Bookings]]></title>
            <link>https://medium.com/@shahanashanmugaraja20/how-captcha-prevents-fake-ipl-ticket-bookings-8e0d2800e342?source=rss-e43999e74116------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e0d2800e342</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[recaptcha]]></category>
            <category><![CDATA[ticket-booking]]></category>
            <category><![CDATA[ipl]]></category>
            <category><![CDATA[captcha]]></category>
            <dc:creator><![CDATA[Shahana Shanmugaraja]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 05:12:48 GMT</pubDate>
            <atom:updated>2025-03-07T05:12:48.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*IbNFuoL7OgtK8f9bIPIk7g.png" /></figure><p>Every IPL season, millions of fans rush to book tickets, but within seconds, they see <strong>“Sold Out!”. </strong>Often, this isn’t just due to high demand — <strong>scalper bots</strong> buy tickets in bulk and later resell them at higher prices, making profits while real fans struggle. To stop this, ticketing platforms use CAPTCHA, which ensures only real humans can book tickets. But how does it work? Let’s find out!</p><h4>How Do Scalper Bots Work ? 🤔</h4><p>Scalper bots are automated programs designed to rapidly purchase high-demand items — such as event tickets, sneakers, or gaming consoles, etc. These bots often use <strong>fake accounts, proxies, and automation scripts</strong> to avoid detection and gain an unfair advantage over genuine buyers. Here’s how they operate :</p><p>1️⃣ <strong>Automated Ticket Purchase:</strong></p><ul><li>Bots monitor ticket sale times and access the booking site instantly when sales go live.</li><li>They fill forms, select seats, and complete purchases at a speed no human can match.</li></ul><p>2️⃣ <strong>Bypassing Security Measures:</strong></p><ul><li>Some advanced bots use fake accounts, proxies, and CAPTCHA-solving services to mimic human behavior.</li><li>They rotate IP addresses to avoid detection.</li></ul><p>3️⃣ <strong>Reselling at Higher Prices:</strong></p><ul><li>Once they secure large numbers of tickets, they list them on resale platforms at inflated prices, exploiting fan demand.</li></ul><p>I recently created a simple form to test the time taken for manual form filling vs an automated script.</p><p>( 🔗 Check out the full code on <a href="https://github.com/Shahana20/Manual-vs-Automated-form-filling">GitHub</a> )</p><p><strong>Manual Entry</strong> — I filled out the form by typing in details like name, email, selecting a match, and entering the number of tickets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*sncSzL7kQCy3BqFLycW35g.png" /></figure><p><strong>Automated Script</strong> — I used an automation script to populate and submit the form instantly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*EbVwRKRfdlEU9Lyfg6mq8A.png" /></figure><p>This shows how easily bots can <strong>exploit</strong> forms. 🚀</p><p>👉 This is exactly where we need<strong> CAPTCHA</strong> to differentiate between human users and automated scripts!</p><h4>How CAPTCHA Stops Scalper Bots ?🚫🤖</h4><p>CAPTCHA stands for <strong>“Completely Automated Public Turing test to tell Computers and Humans Apart”.</strong> It’s a security measure that helps websites differentiate between human users and bots.</p><h4><strong>Challenge-Based Human Verification</strong></h4><p>CAPTCHA introduces challenges that are easy for humans but difficult for bots to solve, such as:</p><p><strong>📝 Text-Based CAPTCHA</strong></p><ul><li>Displays <strong>distorted or warped text</strong> that users must type correctly.</li><li>Bots struggle to recognize distorted characters accurately.</li></ul><p><strong>📷 Image-Based CAPTCHA</strong></p><ul><li>Users must select <strong>images containing specific objects</strong> (e.g., “Select all traffic lights”).</li><li>Bots lack the advanced vision capabilities required to recognize objects reliably.</li></ul><p><strong>✅ reCAPTCHA v2 &amp; v3</strong></p><ul><li><strong>reCAPTCHA v2</strong>: Checkbox <strong>“I’m not a robot”</strong> (analyzes user behavior).</li><li><strong>reCAPTCHA v3</strong>: <strong>Invisible CAPTCHA</strong> that scores user behavior and detects bots automatically.</li></ul><p><strong>🔒 hCaptcha (Privacy-Focused Alternative)</strong></p><ul><li>Functions like reCAPTCHA but focuses on <strong>user privacy,</strong> making it a preferred choice for some websites.</li></ul><p>Since bots depend on speed and automation, solving these challenges complicates their workflow.</p><h4>Working flow of CAPTCHA</h4><ul><li>When a user tries to book a ticket, they <strong>must solve a CAPTCHA challenge</strong>.</li><li>A bot fails to solve the CAPTCHA and gets blocked from proceeding.</li><li>Websites integrate <strong>Google’s reCAPTCHA API</strong>, which sends user responses for backend validation.</li><li>If the response is invalid (bot-like activity detected), the booking request is denied.</li></ul><h4>🤖 Example Scenario:</h4><p>A bot attempts to buy <strong>777</strong> (for a reason :p) IPL tickets by automating form submissions. CAPTCHA appears after multiple attempts, requiring manual input. The bot fails the challenge, preventing it from making bulk purchases.<br><strong>Result:</strong> The tickets remain available for real users instead of resellers.</p><h4>🙁 CAPTCHA Limitations</h4><ul><li>Some advanced bots use machine learning to bypass CAPTCHAs.</li><li>Too many CAPTCHA challenges can frustrate real users.</li><li>CAPTCHA can be challenging for people with disabilities, such as visually impaired users who struggle with image-based CAPTCHAs.</li><li>Advanced bots now simulate mouse movements, clicks, and keystrokes to trick behavioral CAPTCHAs.</li></ul><h3>🔮 The Future of CAPTCHA</h3><p>While CAPTCHA has been a key defense against scalper bots, AI-driven automation is making traditional methods less effective. To counter this, websites are adopting advanced security measures such as behavioral analysis, biometric authentication and Honeypots along with AI-driven fraud detection systems that adapt to emerging threats in real time.</p><p>While no solution is entirely foolproof, CAPTCHA remains a crucial tool in rejecting bot requests. While CAPTCHA alone cannot eliminate bots, it plays a vital role in maintaining fair access and securing online transactions.</p><p>Thank you for taking the time to read this! As technology evolves, so do security measures, and staying informed is key. Feel free to share your thoughts — let’s keep the discussion going! 😊🔐</p><p>Connect with me on <a href="https://www.linkedin.com/in/shahana-shanmugaraja-7b8156243/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e0d2800e342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Nested Attributes in Rails: Building Multi-Step Forms Effectively]]></title>
            <link>https://medium.com/@shahanashanmugaraja20/implementing-nested-attributes-in-rails-building-multi-step-forms-effectively-a5ba2f4bc906?source=rss-e43999e74116------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ba2f4bc906</guid>
            <dc:creator><![CDATA[Shahana Shanmugaraja]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 13:41:57 GMT</pubDate>
            <atom:updated>2025-02-26T13:41:57.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uznl480uxBcL67U9J7nOag.png" /></figure><p><em>Nested attributes in Rails allow you to manage related records through a single form, making them perfect for multi-step forms. In this blog, we’ll explore how nested attributes simplify data handling in complex forms, using a real-world scenario of a fitness tracker.</em></p><h3><strong>Understanding Nested Attributes</strong></h3><p>In Rails, nested attributes are a feature of <strong>Active Record</strong> that allow models to accept and manage attributes of associated records directly through the parent model. This is useful when handling forms with related models, as it enables creating or updating parent and child records in a<strong> single request</strong>.</p><p>Imagine you’re building a fitness tracker where users can log their personal details, fitness status, health information, and workout plans in a <strong>multi-step form</strong>(I’ve covered multi-step forms with React, Formik, and Yup in another blog. Check it out<a href="https://medium.com/@shahanashanmugaraja20/creating-a-multi-step-form-for-a-fitness-tracker-using-react-formik-yup-9119a491a754"> <strong>here!</strong></a>). Nested attributes simplify handling multi-step forms by allowing creation and updation of associated records in a single form submission, making data management more efficient.</p><p>🛠️ <strong>Without Nested Attributes</strong><br>🔹 <strong>Step 1:</strong> Create User → Get user_id<br>🔹 <strong>Step 2:</strong> Create PersonalInfo → Assign user_id manually<br>🔹 <strong>Step 3:</strong> Create FitnessStatus → Assign user_id manually<br>🔹 <strong>Step 4:</strong> Create HealthInfo → Assign user_id manually<br>🔹 <strong>Step 5: </strong>Create WorkoutPlan → Assign user_id manually</p><p>⏳ Multiple DB writes, Explicit user_id assignments, and more controller logic required.</p><p>⚡ <strong>With Nested Attributes</strong> (accepts_nested_attributes_for)<br>🔹 Single Form Submission → User submits all details at once<br>🔹 Rails Automatically Saves All Records → Associations are handled via nested attributes<br>🔹 No Manual ID Assignments → user_id is automatically linked</p><p>🚀 Fewer DB writes, Cleaner Controller Code and easier form management</p><h3><strong>Use of accepts_nested_attributes_for</strong></h3><p>In Rails,<strong> accepts_nested_attributes_for</strong> is a built-in Active Record method that allows a parent model to receive and process attributes for its associated child models in a single request. This is helpful when working with complex data structures, such as multi-step forms, where multiple related records need to be created or updated simultaneously.</p><p>This method modifies how Rails handles mass assignment by permitting nested parameters and automatically building or updating associated records when the parent model is saved. Instead of manually instantiating and saving each associated record, Rails manages them through the parent model’s attributes.</p><h3><strong>Setting Up Nested Attributes in Rails</strong></h3><h4><strong>Step 1 : Define Associations in the User Model</strong></h4><pre>class User &lt; ApplicationRecord<br>  has_one :personal_info, dependent: :destroy<br>  has_one :fitness_status, dependent: :destroy<br>  has_one :health_info, dependent: :destroy<br>  has_one :workout_plan, dependent: :destroy<br><br>  accepts_nested_attributes_for :personal_info, :fitness_status, :health_info, :workout_plan<br>end</pre><p>This allows Rails to accept attributes for the associated models when creating or updating a User record.</p><h4><strong>Step 2 : Permit Nested Attributes in the Controller</strong></h4><pre>def user_params<br>    params.require(:user).permit(<br>      personal_info_attributes: [:name, :age, :gender, :fitness_goal],<br>      fitness_status_attributes: [:height, :weight, :activity_level, :step_count],<br>      health_info_attributes: [:water_intake, :sleep_hours, :dietary_preference, :medical_conditions],<br>      workout_plan_attributes: [:workout_type, :workout_frequency, :need_diet_plan])<br>end</pre><p>In the UsersController, we permit nested attributes in strong parameters to ensure proper data handling.</p><h4><strong>Step 3 : Handling Nested Attributes in the Frontend</strong></h4><p>When working with nested attributes in Rails, the frontend should match the attribute structure to what Rails expects. This avoids issues like <strong>Unpermitted parameters errors or data mismatches. </strong>Rails expects nested attributes to have <strong>_attributes</strong> suffix.</p><p><em>In this example, I’m using React since my multi-step form is built with React</em></p><p>Your React multi-step form will collect user input and send a <strong>POST</strong> request with nested JSON to the Rails backend</p><pre>const finalData = {<br>      user: {<br>        personal_info_attributes: {<br>          name: formData.name,<br>          age: formData.age,<br>          gender: formData.gender,<br>          fitness_goal: formData.fitness_goal<br>        },<br>        fitness_status_attributes: {<br>          height: formData.height,<br>          weight: formData.weight,<br>          activity_level: formData.activity_level,<br>          step_count: formData.step_count<br>        },<br>        //Other Attributes to be followed <br>      }<br>    }</pre><pre>//Sending data to backend<br>const response = await fetch(&quot;http://localhost:3000/api/v1/users&quot;, {<br>                 method: &quot;POST&quot;,<br>                 headers: {&quot;Content-Type&quot;: &quot;application/json&quot;,},<br>                 body: JSON.stringify(finalData)})</pre><h3><strong>Handling Validations</strong></h3><p>When working with nested attributes, it’s essential to ensure data integrity by applying validations at the model level. This prevents incomplete or invalid records from being saved, especially in multi-step forms where multiple related models are involved.</p><h4><strong>Model level validations</strong></h4><pre>class WorkoutPlan &lt; ApplicationRecord<br>  belongs_to :user<br>  has_many :workouts, dependent: :destroy<br>  validates :workouts, presence: true<br>end</pre><h4><strong>Using reject_if</strong></h4><pre>class User &lt; ApplicationRecord<br>  has_one :workout_plan, dependent: :destroy<br>  accepts_nested_attributes_for :workout_plan, reject_if: proc { |attributes| attributes[&#39;workouts&#39;].blank? }<br>end</pre><p>Nested attributes in Rails make handling complex forms with related data much more efficient. By using <strong>accepts_nested_attributes_for</strong>, validations, and structured frontend data handling, you can simplify multi-step form submissions. If you’re interested in seeing the complete implementation, check out my GitHub repository here![<a href="https://github.com/Shahana20/Fitness-Tracker">repo link</a>].</p><p>Thank you for reading! I hope this blog helped you understand how to handle nested attributes in Rails. If you have any questions or thoughts, feel free to share them in the comments. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ba2f4bc906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Multi-Step Form for a Fitness Tracker Using React, Formik & Yup]]></title>
            <link>https://medium.com/@shahanashanmugaraja20/creating-a-multi-step-form-for-a-fitness-tracker-using-react-formik-yup-9119a491a754?source=rss-e43999e74116------2</link>
            <guid isPermaLink="false">https://medium.com/p/9119a491a754</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[yup]]></category>
            <category><![CDATA[formik]]></category>
            <category><![CDATA[multi-step-form]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Shahana Shanmugaraja]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 17:38:11 GMT</pubDate>
            <atom:updated>2025-02-12T17:38:11.273Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Forms are a crucial part of any web application but long, single-page forms can overwhelm users leading to drop-offs. A multi-step form improves user experience by breaking inputs into smaller structured steps. In this blog, we’ll build a fitness tracker form using React, Formik, and Yup, focusing on structured data collection, step-wise navigation, and form validation 🤸.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZUi8LgHcHdAYlki9WooNg.jpeg" /></figure><h4><strong>Why Formik and Yup?</strong></h4><p>In React, manually managing form state and validation can be time consuming and error prone. Formik simplifies form management, while Yup provides a structured way to handle validation. When combined, they make form handling effective, scalable, and clean.</p><h4><strong>What data does a Fitness Tracker require?</strong></h4><p>A fitness tracker form typically asks for <strong>name, age, gender, height, weight, activity level, sleep hours, water intake, diet preference, medical history, and workout preferences</strong>. At first glance, this seems like a lot to fill out. Instead of overwhelming users with a long form, we can enhance the experience by breaking it into logical steps.</p><h4><strong>Breaking it down: A step-by-step approach</strong></h4><p>By structuring the form into smaller steps, we enhance user experience, keeping users engaged and preventing form fatigue. Each step focuses on a specific aspect, ensuring a smooth and intuitive experience. we divide the form into four logical sections :</p><ol><li><strong>Personal Info — </strong>Basic details like name, age, gender, and fitness goals help personalize the experience.</li><li><strong>Current Fitness Status — </strong>Height, weight, activity level and daily step count provide a baseline for tracking progress.</li><li><strong>Health &amp; Lifestyle — </strong>Sleep hours, water intake, diet preferences, and medical conditions help tailor recommendations.</li><li><strong>Workout &amp; Nutrition — </strong>Details like workout type, workout frequency, and whether they need a diet plan ensure a personalized fitness approach.</li></ol><p>Each section builds on the previous one, ensuring a structured and user-friendly experience. Instead of filling out everything at once, users progress step by step, making the form feel more manageable.</p><h4><strong>Setting up Formik</strong></h4><p>Let’s set up Formik in the <strong>Health &amp; Lifestyle</strong> section to see how it manages form state and submission efficiently.</p><p><strong>1)Initialize Formik</strong></p><pre>const formik = useFormik({<br>  initialValues: {<br>    waterIntake: &quot;&quot;,<br>    sleepHours: &quot;&quot;,<br>    dietaryPreference: &quot;&quot;,<br>    medicalConditions: &quot;&quot;,<br>  },<br>  onSubmit: (values) =&gt; {<br>    nextStep(values);<br>  },<br>});</pre><ul><li><strong>useFormik : </strong>Defines form state and submission logic</li><li><strong>initialValues : </strong>Sets default values for each input field.</li><li><strong>onSubmit : </strong>Handles form submission.</li><li><strong>nextStep : </strong>Moves to next step.</li></ul><p><strong>2)Bind Formik to input fields</strong></p><pre>&lt;TextField<br>  label=&quot;Water Intake (Liters/Day)&quot;<br>  type=&quot;number&quot;<br>  {...formik.getFieldProps(&quot;waterIntake&quot;)}<br>/&gt;</pre><ul><li><strong>getFieldProps(“&lt;field-name&gt;”) : </strong>Connects Formik to the specified field.</li></ul><p><strong>3)Handle form submission</strong></p><pre>&lt;form onSubmit={formik.handleSubmit}&gt;<br>  &lt;Button type=&quot;submit&quot;&gt;Next&lt;/Button&gt;<br>&lt;/form&gt;</pre><p>Now that we have set up Formik, the next step is to integrate <strong>Yup</strong> for validation, ensuring that user inputs meet the required criteria.</p><h4><strong>Adding validation with Yup</strong></h4><p>Yup is a schema validation library that works with Formik, allowing us to define rules for each field in a structured way. Instead of manually checking user input, we can define constraints such as required fields, number limits, or predefined options.</p><p>Let’s integrate Yup into our <strong>Health &amp; Lifestyle</strong> section:</p><p><strong>1)Defining validation inside useFormik</strong></p><p>Instead of defining the schema separately, we pass it directly to <strong>useFormik</strong> under the <strong>validationSchema</strong> property</p><pre>validationSchema: Yup.object({<br>    waterIntake: Yup.number()<br>      .min(0, &quot;Enter a valid amount&quot;)<br>      .required(&quot;Required&quot;),<br>    sleepHours: Yup.number()<br>      .min(0, &quot;Enter a valid number of hours&quot;)<br>      .max(24, &quot;Must be less than 24&quot;)<br>      .required(&quot;Required&quot;),<br>    dietaryPreference: Yup.string().required(&quot;Required&quot;),<br>  })</pre><ul><li><strong>waterIntake :</strong> Ensures the value is a positive number and not left empty.</li><li><strong>sleepHours :</strong> Restricts input between 0 and 24 hours.</li><li><strong>dietaryPreference :</strong> Requires the user to select a diet type.</li></ul><p><strong>2)Handling validation in views</strong></p><pre>&lt;TextField<br>  label=&quot;Water Intake (Liters/Day)&quot;<br>  type=&quot;number&quot;<br>  {...formik.getFieldProps(&quot;waterIntake&quot;)}<br>  error={formik.touched.waterIntake &amp;&amp; Boolean(formik.errors.waterIntake)}<br>  helperText={formik.touched.waterIntake &amp;&amp; formik.errors.waterIntake}<br>/&gt;</pre><ul><li><strong>formik.touched.&lt;field-name&gt; :</strong> Checks if the field has been interacted with.</li><li><strong>formik.errors.&lt;field-name&gt; :</strong> Displays error messages only when validation fails.</li></ul><h4><strong>Implementing the Stepper component</strong></h4><p>A stepper helps organize multi-step forms by breaking them into smaller, manageable sections. Let’s integrate a stepper to navigate between form sections.</p><p><strong>1)Defining steps in the stepper</strong></p><pre>const steps = [&quot;Basic Info&quot;, &quot;Current Fitness&quot;, &quot;Health &amp; Lifestyle&quot;, &quot;Workout &amp; Nutrition&quot;];</pre><p><strong>2)Managing active step and form data</strong></p><p>Here, <strong>useState</strong> tracks the current step and form data.</p><pre>const [activeStep, setActiveStep] = useState(0);<br>const [formData, setFormData] = useState({<br>  name: &quot;&quot;,<br>  age: &quot;&quot;,<br>  gender: &quot;&quot;,<br>  fitnessGoal: &quot;&quot;,<br>  height: &quot;&quot;,<br>  weight: &quot;&quot;,<br>  activityLevel: &quot;&quot;,<br>  stepCount: &quot;&quot;,<br>  waterIntake: &quot;&quot;,<br>  sleepHours: &quot;&quot;,<br>  dietPreference: &quot;&quot;,<br>  medicalConditions: &quot;&quot;,<br>  workoutType: &quot;&quot;,<br>  workoutFrequency: &quot;&quot;,<br>  needDietPlan: &quot;&quot;,<br>});</pre><p><strong>3)Navigating between steps</strong></p><pre>const nextStep = (values) =&gt; {<br>  setFormData((prev) =&gt; ({ ...prev, ...values }));<br>  setActiveStep((prevStep) =&gt; prevStep + 1);<br>};<br><br>const prevStep = () =&gt; setActiveStep((prevStep) =&gt; prevStep - 1);</pre><p><strong>4)Rendering the Stepper</strong></p><pre>&lt;Stepper activeStep={activeStep} alternativeLabel&gt;<br>  {steps.map((label, index) =&gt; (<br>    &lt;Step key={index}&gt;<br>      &lt;StepLabel&gt;{label}&lt;/StepLabel&gt;<br>    &lt;/Step&gt;<br>  ))}<br>&lt;/Stepper&gt;</pre><ul><li>Material UI’s stepper visually represents progress</li></ul><p><strong>5)Rendering the form sections</strong></p><pre>&lt;Box&gt;<br>  {activeStep === 0 &amp;&amp; &lt;PersonalInfo nextStep={nextStep} /&gt;}<br>  {activeStep === 1 &amp;&amp; &lt;FitnessStatus nextStep={nextStep} prevStep={prevStep} /&gt;}<br>  {activeStep === 2 &amp;&amp; &lt;HealthAndLifestyle nextStep={nextStep} prevStep={prevStep} /&gt;}<br>  {activeStep === 3 &amp;&amp; &lt;WorkoutAndNutrition prevStep={prevStep} submitForm={submitForm} /&gt;}<br>&lt;/Box&gt;</pre><p><strong>6)Submitting the final form data</strong></p><pre>const submitForm = (values) =&gt; {<br>  setFormData((prev) =&gt; ({ ...prev, ...values }));<br>};</pre><p>The stepper improves user experience by breaking long forms into smaller steps, making navigation easier. This approach ensures smooth data collection across multiple steps.</p><p>You can check out the complete code in my GitHub repository</p><p>🔗 <strong>GitHub Repo : </strong><a href="https://github.com/Shahana20/Multi-Step-form.git">https://github.com/Shahana20/Multi-Step-form.git</a></p><p>This repo contains the full implementation of the stepper component, form validation, and navigation. Feel free to explore, clone, and modify it as needed!</p><p>If you have any questions or suggestions, feel free to reach out. Happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9119a491a754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails Query Optimization: Hitting the Perfect Query]]></title>
            <link>https://medium.com/@shahanashanmugaraja20/rails-query-optimization-hitting-the-perfect-query-6ba893bf7fd3?source=rss-e43999e74116------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ba893bf7fd3</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Shahana Shanmugaraja]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 06:39:29 GMT</pubDate>
            <atom:updated>2025-02-07T06:39:29.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Rails image" src="https://cdn-images-1.medium.com/max/640/1*R_lgf3E2hptM9h3jzGRWaA.png" /></figure><p><em>Optimizing ActiveRecord queries in Rails is just like executing a perfect strategy in a cricket match. It is all about making the right moves to achieve maximum performance. Unoptimized queries can lead to slow applications, wasted resources, and frustration ;-( . In this blog, we’ll tackle common rails query issues and demonstrate how to optimize them for faster, more efficient database performance.</em></p><ol><li><strong>N+1 problem ⚠️</strong></li></ol><p>The N+1 problem occurs when an application makes a series of small, individual queries to retrieve data instead of fetching all the necessary information in a single, efficient query. This approach results in unnecessary database calls, increasing the load on the database and slowing down the application, especially when dealing with large datasets.</p><p>Imagine a cricket coach trying to form a playing 11, but he wants to pick the top 5 batsmen who have the highest batting average. Instead of looking at all players at once and selecting the ones with the highest averages in one go, the coach decides to check each batsman’s average individually.</p><pre>players = Player.limit(1000)  #Fetching all players<br>top_batsmen = []<br><br>players.each do |player|  <br>  if player.player_stat<br>    batting_avg = player.player_stat.batting_avg<br>  else<br>    batting_avg = 0  <br>  end<br>top_batsmen &lt;&lt; { player: player, batting_avg: batting_avg }<br>top_batsmen.sort_by { |batsman| -batsman[:batting_avg] }.first(5)</pre><p><strong>The Solution 💡</strong></p><p>The coach could solve this inefficiency by checking all the players’ batting averages at once, instead of individually. This way, he can avoid making a separate check for each player.</p><p>In database terms, this would be achieved by <strong>eager loading</strong> the necessary stats for all players in a single query, reducing the total number of queries to just 2.</p><pre>players = Player.includes(:player_stat).limit(1000)  <br>top_batsmen = []<br><br># Eager loading<br>players.each do |player| <br>  if player.player_stat<br>    batting_avg = player.player_stat.batting_avg<br>  else<br>    batting_avg = 0  <br>  end<br>top_batsmen &lt;&lt; { player: player, batting_avg: batting_avg }<br>top_batsmen.sort_by { |batsman| -batsman[:batting_avg] }.first(5)</pre><p><strong>Eager Loading<br></strong>Eager loading addresses the N+1 problem by loading all related records in a single query rather than executing a query for each individual record.</p><p><em>In this example, this is done using the</em><strong><em> includes</em></strong><em> method in Rails, which tells ActiveRecord to load the related records upfront</em>. <em>Rails associates the loaded </em><strong><em>player_stats</em></strong><em> with the corresponding players in memory, so when we access </em><strong><em>player.player_stats</em></strong><em> no additional queries are made.</em></p><p><strong>Benchmarking Results for N+1 Query vs Optimized Query</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*zyzZP7lNegQ_6Aw2sPjONg.png" /><figcaption>Benchmarking results</figcaption></figure><p><strong>Without eager loading</strong></p><pre>-- Query 1: Select players<br>SELECT * FROM players LIMIT 1000;<br><br>-- For each player, we run a query to fetch their player_stat (1000 queries)<br>-- Query 2: Select player_stat for player 1<br>SELECT * FROM player_stats WHERE player_id = 1;<br><br>-- Query 3: Select player_stat for player 2<br>SELECT * FROM player_stats WHERE player_id = 2;<br><br>-- .<br>-- .<br><br>-- Query 1001: Select player_stat for player 1000<br>SELECT * FROM player_stats WHERE player_id = 1000;</pre><p><strong>With eager loading</strong></p><pre>-- Query 1: Select players<br>SELECT * FROM players LIMIT 1000;<br><br>-- Query 2: Select player_stats for all players at once<br>SELECT * FROM player_stats WHERE player_id IN (1, 2, 3, ..., 1000);</pre><p>2. <strong>Unoptimized Joins ⚠️</strong></p><p>Unoptimized joins occur when database queries combine data from multiple tables inefficiently, often due to missing indexes on join columns, redundant joins, or improper join types. This leads to slow query execution, increased memory usage, and longer response times, especially when dealing with large tables.</p><p>Now our coach looks for an Indian bowler with 200+ wickets, but he again opts for the unoptimized approach, where he first joins the players table with the player_stats table to get the bowlers, and then joins that result again with the teams table to filter for Indian players.</p><pre>#Inefficient joins<br>players = Player.joins(:team).joins(:player_stat).where(&#39;player_stats.wickets &gt; 200&#39;).limit(1000)<br><br>indian_bowlers = players.select do |player|<br>  player.team.team_name == &#39;India&#39; &amp;&amp; player.role == &#39;Bowler&#39;<br>end</pre><p><strong>The Solution 💡</strong></p><p>The join is now done starting from <strong>player_stats</strong> because we&#39;re primarily concerned with filtering on <strong>wickets</strong>. The query then joins the players table and teams table to get the necessary details, filtering team_name ie., <strong>India</strong> after the first join.</p><pre>players = Player.joins(:player_stat)<br>          .joins(:team)<br>          .where(&#39;player_stats.wickets &gt; 200 AND teams.team_name = ?&#39;, &#39;India&#39;)<br>          .where(role: &#39;Bowler&#39;).limit(1000)</pre><p><strong>Applying filtering conditions</strong></p><p>Optimizing query performance through early filtering can significantly improve execution times. By applying filters before performing joins, we reduce the number of records being processed in the subsequent steps. This is because filtering narrows down the dataset, ensuring that only relevant rows are passed through the joins but performing joins first and filtering afterward can result in unnecessary data being joined, which increases the workload and slows down query performance.</p><p><strong>Benchmarking Results for unoptimized vs optimized join queries</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*QYyAyzDCMy1qiMlQbJyKhw.png" /><figcaption>Benchmarking results</figcaption></figure><p><strong>Without early filtering</strong></p><pre>SELECT players.first_name, players.last_name, player_stats.wickets, teams.team_name<br>FROM players<br>INNER JOIN player_stats ON player_stats.player_id = players.id<br>INNER JOIN teams ON teams.id = players.teams_id<br>WHERE teams.team_name = &#39;India&#39;<br>AND player_stats.wickets &gt;= 200;</pre><p><strong>With early filtering</strong> ( Concerned with filtering on wickets first)</p><pre>SELECT players.first_name, players.last_name, player_stats.wickets, teams.team_name<br>FROM players<br>INNER JOIN player_stats ON player_stats.player_id = players.id<br>INNER JOIN teams ON teams.id = players.teams_id<br>WHERE player_stats.wickets &gt;= 200<br>AND teams.team_name = &#39;India&#39;;</pre><p><strong>3. The SELECT * Problem ⚠️</strong></p><p>The <strong>SELECT *</strong> problem occurs when a query retrieves all columns from a table, even if only a subset of those columns are required. This leads to inefficiencies, especially when dealing with large datasets, as it fetches unnecessary data, increasing execution time and memory usage.</p><p>Again, our coach is on a mission — this time to find the best wicketkeepers based on stumpings and batting averages but of course he takes the <em>“I want it all”</em> approach and opts for SELECT* query (because why learn from past mistakes, right? 🙃).</p><pre>players = Player.includes(:player_stat).limit(1000) #Select all fields<br>wicketkeepers = []<br>    <br>players.each do |player|<br>  player_stat = player.player_stat<br>  stumpings = player_stat.present? ? player_stat.stumpings : 0<br>  batting_avg = player_stat.present? ? player_stat.batting_avg : 0<br>  wicketkeepers &lt;&lt; { player: player.first_name, stumpings: stumpings, batting_avg: batting_avg }<br>end<br>    <br>wicketkeepers.sort_by { |wkt_kpr| [-wkt_kpr[:stumpings], -wkt_kpr[:batting_avg]] }.first(5)</pre><p><strong>The Solution 💡</strong></p><p>Instead of using SELECT* , we only retrieve the necessary columns—<strong>stumpings and batting_avg </strong>from our database. This reduces the amount of data being fetched, leading to faster query execution, lower memory usage and efficient processing.</p><pre>players = Player.includes(:player_stat).references(:player_stat)<br>                .select(&#39;players.first_name, player_stats.stumpings, player_stats.batting_avg&#39;)<br>                .limit(1000) # Selecting only necessary fields<br><br>wicketkeepers = []<br>    <br>players.each do |player|<br>  stumpings = player.player_stat.present? ? player.player_stat.stumpings : 0<br>  batting_avg = player.player_stat.present? ? player.player_stat.batting_avg : 0<br>  wicketkeepers &lt;&lt; { player: player.first_name, stumpings: stumpings, batting_avg: batting_avg }<br>end<br>    <br>wicketkeepers.sort_by { |wkt_kpr| [-wkt_kpr[:stumpings], -wkt_kpr[:batting_avg]] }.first(5)</pre><p><strong>Importance of selecting necessary fields</strong></p><ul><li>Reduced I/O Overhead</li><li>Lower Network Latency</li><li>Efficient Index Utilization</li><li>Faster Data Processing</li><li>Lower Memory Usage</li></ul><p><strong>Benchmarking results for SELECT * vs Selecting relevant fields</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Z6nt4PBgpfCNN6-odXdibw.png" /><figcaption>Benchmarking results</figcaption></figure><p><strong>Using SELECT *</strong></p><pre>SELECT * FROM players<br>INNER JOIN player_stats ON player_stats.player_id = players.id<br>INNER JOIN teams ON teams.id = players.team_id<br>WHERE player_stats.wickets &gt;= 200;</pre><p><strong>Selecting only relevant fields</strong></p><pre>SELECT players.first_name, player_stats.stumpings, player_stats.batting_avg<br>FROM players<br>INNER JOIN player_stats ON player_stats.player_id = players.id<br>WHERE player_stats.wickets &gt;= 200;</pre><p><strong>Conclusion</strong></p><p>To wrap up, optimizing queries by avoiding N+1 issues, inefficient joins, and SELECT * significantly improves performance. Retrieving only essential data and streamlining joins lead to faster execution, lower resource usage, and better application responsiveness</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ba893bf7fd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>