<?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 Giritharan Elangovan on Medium]]></title>
        <description><![CDATA[Stories by Giritharan Elangovan on Medium]]></description>
        <link>https://medium.com/@giri14?source=rss-af9a6a770888------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WYHcn3KHGn3lmP-n</url>
            <title>Stories by Giritharan Elangovan on Medium</title>
            <link>https://medium.com/@giri14?source=rss-af9a6a770888------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:10:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giri14/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[Idempotency in APIs — The Hidden Hero of Payment-Safe Systems]]></title>
            <link>https://medium.com/@giri14/idempotency-in-apis-the-hidden-hero-of-payment-safe-systems-5e4dcd3f61ab?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4dcd3f61ab</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[rails-best-practices]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[railsquery]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 14:13:54 GMT</pubDate>
            <atom:updated>2025-11-28T14:19:16.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Idempotency in APIs — The Hidden Hero of Payment-Safe Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZ5np3Kvi3-xVcCxbLQh1w.png" /></figure><p>Have you ever clicked <strong>“Pay Now”</strong> twice because the button froze?<br>Or lost network while making a request, then retried it?<br>Or received the same webhook twice?</p><p>If your backend isn’t idempotent, these moments can turn into:</p><ul><li>❌ Double payments</li><li>❌ Duplicate records</li><li>❌ Extra ledger entries</li><li>❌ Angry support tickets</li></ul><p>Most backend failures come not from logic — but from <strong>repeated requests</strong>.</p><p>Let’s fix that with idempotency.</p><h3>What is Idempotency?</h3><p>Idempotency means:</p><blockquote><em>Running the same operation multiple times should have the same effect as running it once.</em></blockquote><p>Example scenarios:</p><p>A user taps <strong>Pay</strong> twice → only one payment should go through<br>A webhook fires 3 times → it should be processed only once<br>A client retries due to timeout → the server should return the first successful result</p><p>GET requests are naturally safe.<br>POST requests are <strong>not</strong>, unless we make them idempotent.</p><h3>Why Idempotency Matters (Real World)</h3><p>Payment systems, webhook processors, order creation, crediting wallets — these are all <strong>unsafe</strong> without idempotency.</p><p>Systems like Stripe, Razorpay, PayPal handle this by requiring:</p><pre>Idempotency-Key: &lt;unique uuid&gt;</pre><p>If the same request arrives with the same key, the server should return the <strong>same response</strong>, instead of repeating the action.</p><p>No duplicate charges. No duplicate DB inserts.<br> Just clean, safe behavior.</p><h3>Implementing Idempotency in Rails</h3><p>We are going to build:</p><ul><li>A reusable Rails concern</li><li>A Redis-backed idempotency cache</li><li>Automatic response replay on repeat requests</li><li>An exception if Idempotency-Key is missing</li></ul><p>This is production-tier code.</p><h3>Step 1: Create a custom error</h3><pre># app/errors/missing_idempotency_key_error.rb<br>class MissingIdempotencyKeyError &lt; StandardError; end</pre><h3>Step 2: Idempotency concern</h3><pre># app/controllers/concerns/idempotent_request.rb<br>module IdempotentRequest<br>  extend ActiveSupport::Concern<br><br>  included do<br>    around_action :ensure_idempotency<br>  end<br><br>  private<br><br>  def idempotency_key<br>    request.headers[&#39;Idempotency-Key&#39;].presence<br>  end<br><br>  def ensure_idempotency<br>    raise MissingIdempotencyKeyError, &quot;Idempotency-Key header missing&quot; if idempotency_key.blank?<br><br>    cache_key = &quot;idempotency:#{controller_name}:#{action_name}:#{idempotency_key}&quot;<br><br>    # If request was seen before, return stored output<br>    if (cached = Rails.cache.read(cache_key))<br>      return render json: cached[:body], status: cached[:status]<br>    end<br><br>    # Otherwise process fresh request and store response<br>    response_body = nil<br>    status = nil<br><br>    self.response_body = capture do<br>      yield<br>      response_body = response.body<br>      status = response.status<br>    end<br><br>    Rails.cache.write(cache_key, { body: response_body, status: status }, expires_in: 24.hours)<br><br>    render json: response_body, status: status<br>  end<br>end</pre><h3>Step 3: Use inside your controller</h3><pre>class PaymentsController &lt; ApplicationController<br>  include IdempotentRequest<br><br>  rescue_from MissingIdempotencyKeyError do |e|<br>    render json: { error: e.message }, status: 422<br>  end<br><br>  def create<br>    payment = Payment.create!(amount: params[:amount])<br>    render json: payment, status: :created<br>  end<br>end</pre><p>Now let’s translate this into simple behavior:</p><ul><li>If <strong>Idempotency-Key is missing</strong> → request rejected</li><li>First request → payment created and cached</li><li>Second request with the same key → returns the same response, without creating a new payment</li></ul><p>This is exactly how payment gateways guarantee safety</p><h3>Extra Safety Trick — Detect Modified Requests</h3><p>If someone uses the same Idempotency-Key but changes payload, we should block it.</p><pre>signature = Digest::SHA256.hexdigest(request.raw_post)<br>cached = Rails.cache.read(cache_key)<br><br>if cached &amp;&amp; cached[:signature] != signature<br>  return render json: { error: &quot;Different payload for same Idempotency-Key&quot; }, status: 409<br>end</pre><p>Prevents misuse, fraud &amp; logical corruption.</p><h3>🏁 Final Thoughts</h3><p>Use it wherever retries may cause damage:</p><ul><li>Payments, refunds, payouts</li><li>Webhooks processing</li><li>Ledger / accounting writes</li><li>Money movement of any kind</li></ul><p>If a retry can break data — make it idempotent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4dcd3f61ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Freedium Is Not Working — and the New Working Link (freedium-mirror.cfd)]]></title>
            <link>https://medium.com/@giri14/why-freedium-is-not-working-and-the-new-working-link-freedium-mirror-cfd-4e2c29b54f63?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e2c29b54f63</guid>
            <category><![CDATA[freedium]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 05:49:53 GMT</pubDate>
            <atom:updated>2025-10-27T05:49:53.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Freedium Is Not Working — and the New Working Link (freedium-mirror.cfd)</h3><p>If you’ve been using <strong>Freedium</strong> to read Medium articles without hitting paywalls, you might have noticed recently that <strong>Freedium stopped working</strong> or some links no longer load properly.</p><p>You’re not alone — this issue has been widely reported by users on <a href="https://github.com/Freedium-cfd/web/issues/37#issuecomment-3370656846">Freedium’s GitHub</a>. The team behind Freedium confirmed that there have been disruptions and domain access problems, but they’re actively working on keeping access open for everyone.</p><h3>✅ The Latest Working Freedium URL</h3><p>The official Freedium team has now launched a new domain:</p><p>👉 <a href="https://freedium-mirror.cfd/"><strong>freedium-mirror.cfd</strong></a></p><p>This is the latest working mirror you can use to continue accessing Medium articles without paywalls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e2c29b54f63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ActiveRecord’s joins, left_outer_joins, and includes in Rails]]></title>
            <link>https://medium.com/@giri14/understanding-activerecords-joins-left-outer-joins-and-includes-in-rails-cd696bd3d0ce?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd696bd3d0ce</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 08:15:12 GMT</pubDate>
            <atom:updated>2025-04-24T08:15:12.649Z</atom:updated>
            <content:encoded><![CDATA[<p>In Rails, when working with ActiveRecord queries, you can use joins, left_outer_joins, and includes to handle associations between models. These methods are key to optimizing database queries and fetching related data.</p><p>Let’s break down what each one does and how they differ from each other.</p><h3>joins: The Inner Join</h3><p>The joins method is used to perform an <strong>INNER JOIN</strong>. This means that only records with matching associations are returned.</p><p>For example, if you want to get users who have posts, you would use:</p><pre>User.joins(:posts)</pre><p>This query will return users who <strong>must</strong> have posts. If a user has no posts, they will not be included in the result set.</p><h3>left_outer_joins: The Left Outer Join</h3><p>The left_outer_joins method performs a <strong>LEFT OUTER JOIN</strong>. This means all records from the main table will be returned, even if there is no match in the associated table.</p><p>For example:</p><pre>User.left_outer_joins(:posts)</pre><p>This will return <strong>all users</strong>, even those who don’t have posts. For users without posts, the posts-related fields will be nil.</p><p>The left_outer_joins method is useful when you want to find records that may or may not have an associated record in another table.</p><h3>includes: Eager Loading Associations</h3><p>The includes method is used for <strong>eager loading</strong> associations. It loads the associated data in advance to avoid the <strong>N+1 query problem</strong>. When using includes, two separate queries are made—one for the main table and another for the associated table.</p><p>Example:</p><pre>User.includes(:posts).each do |user|<br>  user.posts.each do |post|<br>    puts post.title<br>  end<br>end</pre><p>This will load all users and their posts in two queries. This prevents fetching the posts for each user one by one.</p><p>If there are no associated records, includes will return an empty array [] for has_many associations or nil for belongs_to associations.</p><h3>Summary</h3><ul><li><strong>joins</strong>: Only returns records that have matching associations.</li><li><strong>left_outer_joins</strong>: Returns all records, even without matching associations.</li><li><strong>includes</strong>: Eager loads associations to prevent N+1 queries and returns empty arrays or nil for missing associations.</li></ul><p>Each method has its specific use case, and choosing the right one depends on your needs. Use joins when filtering by associations, left_outer_joins for including records with missing associations, and includes when you want to avoid N+1 queries and load all associated records in advance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd696bd3d0ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering preload, includes, and eager_load in Rails: A Guide to Smarter Querying]]></title>
            <link>https://medium.com/@giri14/mastering-preload-includes-and-eager-load-in-rails-a-guide-to-smarter-querying-906872f725c7?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/906872f725c7</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[querying]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 08:04:09 GMT</pubDate>
            <atom:updated>2025-04-24T08:05:45.757Z</atom:updated>
            <content:encoded><![CDATA[<p>When building Rails apps, performance often hinges on how efficiently we fetch data from the database. One of the most common (and sneaky) performance killers is the <strong>N+1 query problem</strong>. Thankfully, Rails provides powerful tools to eliminate it: preload, includes, and eager_load.</p><p>But when should you use which? 🤔<br> Let’s break it down, compare them side by side, and help you master query optimization like a pro.</p><h3>🚨 The N+1 Query Problem (Quick Refresher)</h3><p>Let’s say you’re listing posts and their comments:</p><pre>@posts = Post.all<br><br>@posts.each do |post|<br>  post.comments.each do |comment|<br>    puts comment.body<br>  end<br>end</pre><p>This executes:</p><ul><li>1 query for all posts</li><li>1 additional query <strong>per post</strong> to fetch its comments</li></ul><p>That’s N+1 queries — one for the posts, and one per post for comments. It <em>kills</em> performance at scale.</p><h3>🛠 Rails to the Rescue: preload, includes, eager_load</h3><p>These methods solve N+1 queries by <strong>eager loading</strong> associations — but they do it differently.</p><h3>🔹 preload – Simple, No JOINs</h3><p>preload fetches associated records in <strong>separate queries</strong> and assembles them in memory.</p><pre>@posts = Post.preload(:comments)</pre><p>🔍 Rails runs:</p><ul><li>One query to fetch posts</li><li>One query to fetch comments for all those posts</li></ul><p>✅ Use when:</p><ul><li>You’re <strong>just displaying</strong> associations</li><li>You <strong>don’t need filtering or sorting</strong> by the associated model</li></ul><h3>🔸 eager_load – Always JOINs</h3><p>eager_load always performs a <strong>SQL LEFT OUTER JOIN</strong>, loading everything in one query.</p><pre>@posts = Post.eager_load(:comments).where(comments: { user_id: 1 })</pre><p>✅ Use when:</p><ul><li>You’re <strong>filtering or sorting</strong> by the associated model</li><li>You want <strong>complete control</strong> over the SQL being executed</li></ul><p>⚠️ Be careful: eager_load can bring in lots of data you might not use, because of the join.</p><h3>🔄 includes – The Smart Hybrid</h3><p>includes is Rails’ smart option — it behaves like either preload or eager_load depending on your query.</p><pre># behaves like preload (2 queries)<br>@posts = Post.includes(:comments)<br><br># behaves like eager_load (1 JOIN query)<br>@posts = Post.includes(:comments).where(comments: { user_id: 1 })</pre><p>✅ Use when:</p><ul><li>You might or might not filter/sort by the associated data</li><li>You want to keep your code <strong>clean and adaptable</strong></li></ul><h3>📊 Comparison: preload vs includes vs eager_load</h3><h3>🔹 preload</h3><ul><li><strong>Queries:</strong> Always 2 (main and association)</li><li><strong>Joins:</strong> ❌ No JOINs</li><li><strong>Filtering/Sorting on association:</strong> ❌ Not supported</li><li><strong>Performance:</strong> ✅ Great for simple use cases</li><li><strong>Best for:</strong> Displaying associations without filtering</li></ul><h3>🔸 includes</h3><ul><li><strong>Queries:</strong> 1 or 2 (smart behavior)</li><li><strong>Joins:</strong> ✅ Uses JOIN <em>only if needed</em></li><li><strong>Filtering/Sorting on association:</strong> ✅ Supported</li><li><strong>Performance:</strong> ✅ Good balance of flexibility and efficiency</li><li><strong>Best for:</strong> Default choice when unsure — flexible and adaptive</li></ul><h3>⚡ eager_load</h3><ul><li><strong>Queries:</strong> Always 1</li><li><strong>Joins:</strong> ✅ Always uses LEFT OUTER JOIN</li><li><strong>Filtering/Sorting on association:</strong> ✅ Fully supported</li><li><strong>Performance:</strong> ⚠️ Can be heavy if unused data is fetched</li><li><strong>Best for:</strong> Advanced filtering or sorting with JOINs</li></ul><h3>🧠 TL;DR</h3><ul><li>Use <strong>preload</strong> when you just want to display associated data and avoid joins.</li><li>Use <strong>eager_load</strong> when you need to <strong>filter or sort</strong> using associated records — and want guaranteed JOIN behavior.</li><li>Use <strong>includes</strong> when you want the best of both — flexibility with performance.</li></ul><h3>🔚 Final Thoughts</h3><p>Choosing the right eager loading method in Rails isn’t just about eliminating N+1 queries — it’s about <strong>writing efficient, scalable queries</strong> that keep your app blazing fast.</p><p>When in doubt, start with includes. Then optimize with preload or eager_load depending on your exact needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906872f725c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Speed Up Queries with Nested Scopes in Rails]]></title>
            <link>https://medium.com/@giri14/speed-up-queries-with-nested-scopes-in-rails-3d9bcafb6519?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d9bcafb6519</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 07:52:52 GMT</pubDate>
            <atom:updated>2025-04-24T07:52:52.391Z</atom:updated>
            <content:encoded><![CDATA[<p>When working on a recent Rails project, I faced a challenge that many of us encounter — optimizing complex queries while dealing with multiple associated models. To tackle this efficiently, I leveraged <strong>**nested scopes**</strong> and some powerful ActiveRecord features. Let’s walk through the basics, and then we’ll dive into how to apply nested scopes for advanced querying.</p><p><strong>🔍 A Quick Refresher: What is Query Optimization?</strong></p><p>Query optimization is crucial for delivering fast and efficient applications. A common performance bottleneck in Rails apps is the infamous <strong>N+1 query problem.</strong></p><p><strong>❗ What are N+1 Queries?</strong></p><p>Let’s take this example:</p><pre>class Post &lt; ApplicationRecord<br>has_many :comments<br>end<br>@posts = Post.all<br>@posts.each do |post|<br>post.comments.count<br>end</pre><p>This code:</p><ul><li>Loads all posts in one query (<strong>N</strong>)</li><li>Loads comments for <strong>each</strong> post in a separate query (<strong>+1</strong> per post)</li></ul><p>This results in <strong>N+1 queries</strong>, slowing down the application significantly.</p><p><strong>✅ Solving N+1 with <em>preload</em> and <em>includes</em></strong></p><p><strong>🔹 When to Use <em>preload</em></strong></p><p>Use <strong>preload</strong> when you’re iterating over associations but <strong>not filtering</strong> them.</p><pre>@posts = Post.preload(:comments)<br>@posts.each do |post|<br>post.comments.each do |comment|<br>puts comment.body<br>end<br>end</pre><p>This performs <strong>two separate queries</strong> — one for posts and one for comments.</p><p><strong>� When to Use <em>includes</em></strong></p><p>Use <strong>includes</strong> when you <strong>might</strong> filter associated data.</p><pre>user = User.includes(:posts).where(posts: { title: &quot;Rails&quot; }).first</pre><p>Since we’re filtering by <strong>posts.title</strong>, Rails smartly uses a <strong>JOIN</strong> (via <strong><em>eager_load</em></strong>) instead of separate queries.</p><p><strong>🚀 Taking It Further: Nested Scopes</strong></p><p>Let’s level up.</p><p>Imagine the following scenario with three models:</p><pre>class User &lt; ApplicationRecord<br>has_many :posts<br>has_many :comments<br>has_many :recent_posts, -&gt; { recent }, class_name: &quot;Post&quot;<br>end<br><br>class Post &lt; ApplicationRecord<br>belongs_to :user<br>has_many :comments<br>has_many :recent_comments, -&gt; { recent }, class_name: &quot;Comment&quot;<br>scope :recent, -&gt; { where(date: (Date.yesterday..Date.today)) }<br>end<br><br>class Comment &lt; ApplicationRecord<br>belongs_to :post<br>belongs_to :user<br>scope :recent, -&gt; { where(date: (Date.yesterday..Date.today)) }<br>end</pre><p>We’ve added:</p><p>- <strong><em>recent</em></strong> scopes to fetch data from the last two days</p><p>- <strong><em>recent_posts</em></strong> and <strong><em>recent_comments</em></strong> associations to access recent data more intuitively</p><p><strong>Scenario:</strong></p><p><strong>Fetch a specific user’s recent posts that have recent comments added by an admin user.</strong></p><p><strong>❌ What didn’t work:</strong></p><pre>@user.recent_posts<br>.recent_comments<br>.where(comments: { user_id: admin.id })</pre><p>This fails because <strong><em>recent_comments</em></strong> is a scope on <strong>Post</strong>, not on a collection of posts.</p><p><strong>✅ What Worked:</strong></p><pre>filtered_posts = @user.recent_posts<br>.includes(comments: :user)<br>.where(comments: { user_id: admin.id })<br>.merge(Comment.recent)</pre><p><strong>💡 Explanation:</strong></p><p>- .<strong><em>recent_posts</em></strong> fetches the user’s recent posts</p><p>- <strong><em>.includes(comments: :user)</em></strong> eager-loads comments and their authors</p><p>- .<strong><em>where</em></strong> filters comments by the admin user</p><p>- <strong><em>.merge(Comment.recent)</em></strong> applies the <strong><em>recent</em></strong> scope from the <strong>Comment</strong> model</p><p>This combo allows us to <strong>chain scopes</strong> and <strong>filter efficiently</strong>, all while avoiding N+1 queries. You can swap <strong><em>includes</em></strong> with <strong><em>joins</em></strong> if you don’t need eager loading, and want strict filtering at the database level.</p><p><strong>🎯 Conclusion</strong></p><p>By using nested scopes, <strong>includes</strong>, and <strong>merge</strong>, you can write expressive, powerful, and performant ActiveRecord queries. It’s not just about writing less code — it’s about writing the right code for better performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d9bcafb6519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bangalore to Kolukkumalai — A Birthday Trip on Two Wheels]]></title>
            <link>https://medium.com/@giri14/bangalore-to-kolukkumalai-a-birthday-trip-on-two-wheels-8665b8a9e6ad?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/8665b8a9e6ad</guid>
            <category><![CDATA[birthday]]></category>
            <category><![CDATA[traveling]]></category>
            <category><![CDATA[friendship]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[friends]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 12:23:52 GMT</pubDate>
            <atom:updated>2026-04-02T13:54:30.172Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Bangalore to Kolukkumalai — A Birthday Trip on Two Wheels</strong></h3><h3>Bangalore to Kolukkumalai — A Birthday Trip on Two Wheels</h3><p><em>Day 1 — Night Rides, Fights, and Flashlight Cakes</em><br> <strong>Date: 19.04.2025</strong></p><p>I’m not the kind of person who enjoys long bike rides. Honestly, I’d rather travel comfortably, but sometimes, friendships pull you into unexpected adventures. That’s exactly what happened when my friend emotionally blackmailed me into joining a bike trip from Bangalore to Kolukkumalai, Kerala — to celebrate his birthday.</p><h3>The Journey Begins</h3><p>We left Bangalore on <strong>Thursday night</strong> and rode through the darkness, eventually reaching my friend’s house in <strong>Namakkal</strong> around <strong>5 AM</strong>. It was my <strong>first-ever night ride</strong>, and it felt surreal. We caught a few hours of sleep and woke up around <strong>10 AM</strong>.</p><p>There were four of us. As we took turns getting refreshed, I ended up chatting with my friend’s dad — a surprisingly wholesome moment. After breakfast, we visited his new under-construction house and then hit the road again.</p><h3>The Scenic Stops</h3><p>Our first memorable stop was at <strong>Mayanur Bridge</strong> — the view there was calm and beautiful, a perfect moment to breathe. After that, we picked up speed and rode along the <strong>Trichy-Karur highway</strong>. We stopped at a petrol bunk to refuel, and the scenery there just hit different. We took a quick break at <strong>Erayodu</strong> for a refreshing coconut drink.</p><p>But not everything was smooth — Birthday boy had a fight with his girlfriend during the ride. She wasn’t happy about this long-distance bike trip (it’s about <strong>500 km</strong> from Bangalore to Munnar, after all). We had to pause and cool things down a bit.</p><h3>Into the Hills</h3><p>By around <strong>4 PM</strong>, we reached <strong>Theni</strong>, cruising past beautiful mountain landscapes and flocks of birds flying through the hills. We had lunch at a cozy hotel near the bus stand — great food that hit the spot after a long ride.</p><p>From there, we headed towards <strong>Suriyanelli</strong> via <strong>Bodi</strong> and <strong>Bodimettu</strong>. Just before reaching, we stopped at a scenic viewpoint — quiet, peaceful, and absolutely stunning. Later, we checked into our resort, freshened up, and headed out for dinner. But yep, the fight from earlier was still going on…</p><h3>The Secret Birthday Plan</h3><p>Back at the room after dinner, my friend and I decided to surprise the birthday boy. We tried sneaking out to buy a cake but — classic — he caught us. We told him we were just grabbing snacks.</p><p>At the local bakery, we asked for a birthday cake, but the guy told us you had to pre-order cakes in Suriyanelli. Big letdown. So we improvised — grabbed a small regular cake, one candle, a plastic knife, and some biscuits. When we got back to the room, we played it cool and acted like we only bought the biscuits.</p><p>Our friend, the birthday boy, looked suspicious. He thought we’d bought tomatoes and eggs to prank him at midnight. We played along. He warned us: “If you throw anything at me, I’ll throw it right back!” 😂</p><h3>Flashlights &amp; Childhood Games</h3><p>Then — boom — power cut. We switched on our flashlights and started playing silly childhood games, waiting for midnight. It felt nostalgic, like we were kids again on a sleepover.</p><p>At <strong>12 AM</strong>, we lit the candle, cut the cake, birthday boy got call from his family, and had a small but heartfelt birthday celebration. After that, we crashed — tired, happy, and ready for what Day 2 would bring.</p><h3><strong>Day 2 — Sunrise Views, Cold Weather, and the Final Ride</strong></h3><p>After all the laughter and fun from the birthday celebration, we didn’t sleep immediately. We roamed around the resort for a while. The place had some guavas and other fruits… which we may or may not have “borrowed” 😄. Eventually, we crashed, excited for what Day 2 had in store.</p><p>We woke up around 6 AM, got refreshed, and had breakfast at Suriyanelli. From there, we headed towards Vattavada. Even while writing this now, I still feel amazed thinking about that place.</p><p>Trips like these are always special — they bring peace and change your perspective. While riding, it felt like we were flying alongside birds, breathing with the trees, and surrounded by the raw scent of nature. Just… wow. What a moment.</p><p>On the way, we crossed dams, small villages, and even got lucky enough to spot an elephant. The route to Vattavada takes you through a forest stretch of about 10–12 km, and that part was absolutely incredible — lush greenery, grass-covered landscapes, and bumpy roads that made it feel like a true adventure.</p><p>Vattavada is a place surrounded by mountains — you literally stand between them. I personally felt like I was one small part of something so much bigger. There were strawberry farms, and we met some really warm, Tamil-speaking locals. There’s something special about meeting people from your own culture in a completely different place — it just hits differently.</p><p>We stayed there for the night — ate well, had a few drinks, laughed a lot, and slept peacefully.</p><p>And then came the hardest part — heading back to Bangalore.</p><p>Honestly, none of us felt like leaving. Trips like this make you forget everything else, and once you’re in that moment, you never want it to end. But reality calls.</p><p>With tired bodies, full hearts, and a bag full of memories, we finally made our way back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8665b8a9e6ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding OAuth and OpenID Connect — A Complete Guide]]></title>
            <link>https://medium.com/@giri14/understanding-oauth-and-openid-connect-a-complete-guide-36dca1f6dfe6?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/36dca1f6dfe6</guid>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 11:45:15 GMT</pubDate>
            <atom:updated>2025-04-22T11:52:40.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔐 Understanding OAuth and OpenID Connect — A Complete Guide</h3><p>In today’s digital world, almost every app needs to access user data — but safely. You’ve probably seen “Login with Google” or “Connect to GitHub” buttons. Ever wondered what magic is going on behind the scenes?</p><p>That magic is powered by <strong>OAuth</strong> and sometimes <strong>OpenID Connect</strong>.</p><p>But here’s the kicker: People often confuse authorization with authentication. Let’s break it all down — clearly and completely.</p><h3>🧭 What is OAuth?</h3><p><strong>OAuth</strong> (Open Authorization) is an open standard that allows third-party apps to access user data — like your email, calendar, or photos — <strong>without asking for your password</strong>.</p><p>Instead of handing over credentials, the user grants limited access using <strong>tokens</strong>. These tokens are then used to access specific resources.</p><h3>✅ OAuth is About Authorization, Not Authentication</h3><p>This is a key distinction.</p><p><strong>Authorization</strong> answers the question:</p><blockquote><em>“Is this app allowed to do this on behalf of the user?”</em></blockquote><p><strong>Authentication</strong>, on the other hand, answers:</p><blockquote><em>“Who is this user?”</em></blockquote><p>OAuth handles <strong>authorization</strong>. That’s it. But here’s where things get fuzzy…</p><h3>😕 Then Why Do People “Log In With Google” Using OAuth?</h3><p>While OAuth wasn’t designed for authentication, developers began using it for that purpose. But to really support authentication — verifying who the user is — we need something more.</p><h3>👤 What is OpenID Connect (OIDC)?</h3><p><strong>OpenID Connect</strong> is a layer built <strong>on top of OAuth 2.0</strong>. It adds an <strong>identity layer</strong>, which means it not only allows access to user data but also provides details about the user — like their name, email, and profile picture.</p><p>In other words, OIDC lets you <strong>log in</strong> users securely.</p><p>So when you click “Sign in with Google,” what’s actually happening is:</p><ul><li>OAuth 2.0 is used to get a token.</li><li>OpenID Connect uses that token to verify <strong>who you are</strong>.</li></ul><h3>🔄 Versions of OAuth: 1.0 vs 2.0</h3><p>OAuth has two major versions: 1.0 (technically 1.0a) and 2.0. They differ in complexity, security, and use cases.</p><h3>OAuth 1.0</h3><ul><li>Released in 2007.</li><li>Uses <strong>cryptographic signatures</strong> to verify each request.</li><li>Secure, but complex to implement.</li><li>Requires more steps to get access tokens.</li><li>Mostly used in the past; now considered obsolete.</li></ul><h3>OAuth 2.0</h3><ul><li>Released in 2012.</li><li>More flexible and easier to use.</li><li>Uses <strong>bearer tokens</strong>, meaning whoever has the token can access the resource.</li><li>Built for modern applications — web, mobile, and IoT.</li><li>Can be extended (which is how OIDC works).</li><li>Widely used today (Google, Facebook, GitHub, etc.).</li></ul><h3>🔍 Key Differences Between OAuth 1.0 and OAuth 2.0</h3><ul><li>OAuth 1.0 signs every request with complex cryptographic methods, while OAuth 2.0 just uses bearer tokens (simpler, but relies on HTTPS for security).</li><li>OAuth 1.0 has one flow for all use cases. OAuth 2.0 supports multiple flows (for web apps, mobile apps, server-to-server, etc.).</li><li>OAuth 2.0 is more extensible — it powers not just APIs, but also login systems through OpenID Connect.</li><li>OAuth 1.0 is no longer recommended for new applications. OAuth 2.0 is the current standard.</li></ul><h3>🎯 OAuth vs OpenID Connect: What’s the Real Difference?</h3><p>Here’s the bottom line:</p><ul><li><strong>OAuth 2.0</strong> lets apps access <strong>user data</strong> with permission.</li><li><strong>OpenID Connect</strong> lets apps <strong>identify</strong> the user — it’s used for <strong>logging in</strong>.</li></ul><p>OAuth gives you access to data. OpenID Connect gives you details about the user. You can think of OAuth as the <strong>key to the building</strong>, and OIDC as the <strong>“ID badge”</strong> of the person holding the key.</p><h3>🛡️ Security Considerations</h3><p>While OAuth 2.0 is easier to implement, it relies heavily on <strong>secure HTTPS connections</strong>. If the token is stolen, the attacker can use it. So it’s important to:</p><ul><li>Always use HTTPS.</li><li>Use <strong>short-lived tokens</strong> and <strong>refresh tokens</strong>.</li><li>Validate <strong>scopes</strong> — only give access to what’s needed.</li><li>Use <strong>PKCE</strong> in mobile or JavaScript apps.</li><li>Don’t store tokens in insecure places (like localStorage).</li></ul><h3>✍️ Final Thoughts</h3><p>OAuth and OpenID Connect are everywhere — from social media logins to enterprise integrations. But understanding the difference between <strong>authorization</strong> (OAuth) and <strong>authentication</strong> (OIDC) is critical.</p><p>Here’s a quick recap:</p><ul><li><strong>OAuth</strong>: Allows apps to access data <strong>on behalf of a user</strong>.</li><li><strong>OAuth 1.0</strong>: Secure but complex. Largely outdated.</li><li><strong>OAuth 2.0</strong>: Simpler, modular, and widely used today.</li><li><strong>OpenID Connect</strong>: Adds authentication on top of OAuth 2.0, making “Login with…” possible.</li></ul><p>So next time you click “Log in with Google,” you’ll know the tech powering it and why it’s not just OAuth doing the work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36dca1f6dfe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate Ruby on Rails Command Cheat Sheet]]></title>
            <link>https://medium.com/@giri14/ultimate-ruby-on-rails-command-cheat-sheet-1abaaac41354?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/1abaaac41354</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 19:42:35 GMT</pubDate>
            <atom:updated>2025-04-16T19:42:35.292Z</atom:updated>
            <content:encoded><![CDATA[<p>📌 <em>Originally published by </em><a href="https://medium.com/@ronakabhattrz/essential-rails-7-8-commands-guide-a1579cb9d012"><strong><em>Ronak Bhatt</em></strong></a><em>.<br> Republished here broader community reach.</em></p><p>Whether you’re spinning up a fresh Rails app or deploying to production, this guide covers the essential commands for Rails 7 and 8 — including database operations, component generation, frontend integration, testing, and more.</p><p>Perfect for developers who want a quick-reference guide that saves time and avoids Googling every little thing. Let’s dive in 👇</p><h3>🛠 Project Setup and Management</h3><h3>Create a New Rails App</h3><pre># Basic app with default settings<br>rails new myapp<br><br># Use specific database<br>rails new myapp --database=postgresql<br>rails new myapp --database=mysql<br>rails new myapp --database=sqlite3<br><br># API-only application<br>rails new myapp --api<br><br># Minimal setup without default gems<br>rails new myapp --minimal<br><br># Frontend options (Rails 7+)<br>rails new myapp --css tailwind<br>rails new myapp --css bootstrap<br>rails new myapp --css bulma<br>rails new myapp --javascript esbuild<br>rails new myapp --javascript webpack<br>rails new myapp --javascript importmap<br><br># Skip optional components<br>rails new myapp --skip-test<br>rails new myapp --skip-system-test<br>rails new myapp --skip-active-storage<br>rails new myapp --skip-action-mailbox<br>rails new myapp --skip-action-text</pre><p>🗄 Database Operations</p><pre># Create and setup<br>rails db:create<br>rails db:migrate<br>rails db:seed<br>rails db:reset        # drop, create, migrate<br>rails db:drop<br><br># Rollback and control<br>rails db:rollback STEP=1<br>rails db:migrate:status<br>rails db:version<br>rails db:schema:load<br>rails db:structure:load<br>rails db:setup<br>rails db:prepare<br>rails db:environment:set RAILS_ENV=production<br><br># Schema caching<br>rails db:schema:cache:clear<br>rails db:schema:cache:dump<br><br># Specific migration control<br>rails db:migrate:down VERSION=20230101000000<br>rails db:migrate:up VERSION=20230101000000</pre><p>⚙️ Model Generation</p><pre># Simple model<br>rails generate model User name:string email:string:uniq age:integer<br><br># With references<br>rails generate model Comment content:text user:references post:references<br><br># With validations and constraints<br>rails generate model Product name:string{30} price:decimal{10,2}<br><br># Advanced examples<br>rails generate model User admin:boolean default:false<br>rails generate model Article slug:string:uniq title:string{100} body:text published_at:datetime<br>rails generate model Profile user:belongs_to bio:text social_links:json<br>rails generate model Category name:string position:integer:index</pre><p>🎮 Controller Generation</p><pre># With actions<br>rails generate controller Users index show create update destroy<br><br># API controller<br>rails generate controller api/v1/Users index show --skip-template-engine<br><br># Namespaced<br>rails generate controller Admin::Dashboard index<br><br># Additional options<br>rails generate controller Posts --skip-routes<br>rails generate controller Comments --skip-helper<br>rails generate controller Admin::Products --skip-assets<br>rails generate controller Api::V2::Users --skip-template-engine --api</pre><p>🚀 Advanced Generators</p><pre># Mailers<br>rails generate mailer UserMailer welcome_email password_reset<br><br># Jobs<br>rails generate job process_payment<br>rails generate job send_notifications --queue urgent<br><br># Channels<br>rails generate channel room speak<br><br># Serializers<br>rails generate serializer user name email role<br><br># StimulusJS<br>rails generate stimulus form_validation</pre><p>🧪 Testing Framework</p><pre># Run all tests<br>rails test<br><br># Specific tests<br>rails test test/models/user_test.rb<br>rails test test/controllers<br>rails test test/integration<br><br># Config options<br>rails test -v            # Verbose<br>rails test --fail-fast   # Stop on failure<br>rails test --seed 12345  # Specific seed<br><br># System Tests<br>rails test:system<br>rails generate system_test users<br>rails test:system -v<br><br># Performance Tests<br>rails generate performance_test browsing<br>rails test:performance<br><br># Parallel Testing<br>rails test:parallel<br>rails test:prepare</pre><p>🧰 Development &amp; Debugging Tools</p><pre># Server commands<br>rails server -p 4000<br>rails server -b 0.0.0.0<br>rails server -e production<br>rails server -d<br><br># Rails console<br>rails console --sandbox<br>rails console -e production<br>rails console test<br><br># Debugging<br>rails stats<br>rails notes<br>rails middleware<br>rails runner &#39;puts User.count&#39;<br><br># Routes<br>rails routes -g users<br>rails routes -c Users<br>rails routes --expanded</pre><p>🎨 Asset Pipeline &amp; Webpacker</p><pre># Asset pipeline<br>rails assets:precompile<br>rails assets:clean<br>rails assets:clobber<br>rails assets:environment<br>rails assets:precompile:all<br><br># Webpacker (if using)<br>rails webpacker:install<br>rails webpacker:compile<br>rails webpacker:clean<br>rails webpacker:clobber</pre><p>🚀 Production &amp; Deployment</p><pre># Setup<br>rails credentials:edit --environment production<br>rails db:migrate RAILS_ENV=production<br>rails assets:precompile RAILS_ENV=production<br><br># Secrets<br>rails secret<br>rails credentials:show<br>rails encrypted:edit config/master.key<br><br># Caching<br>rails dev:cache<br>rails tmp:cache:clear<br>rails tmp:clear</pre><p>⚡ Rails 7+ Modern Frontend</p><pre># Turbo and Stimulus<br>rails turbo:install<br>rails turbo:install:redis<br>rails stimulus:install<br><br># Importmap<br>bin/importmap pin @hotwired/turbo-rails<br>bin/importmap pin @hotwired/stimulus<br>bin/importmap pin lodash --download<br>bin/importmap json<br><br># CSS Setup<br>rails css:install:tailwind<br>rails css:install:bootstrap<br>rails css:install:postcss<br>rails css:install:sass</pre><p>🧼 Database Maintenance &amp; Troubleshooting</p><pre># Schema tools<br>rails db:schema:dump<br>rails db:structure:dump<br>rails db:version<br><br># Analysis &amp; validation<br>rails db:analyze<br>rails db:validate<br>rails db:seed:replant<br><br># Backups<br>rails db:_dump<br>rails db:abort_if_pending_migrations<br><br># General cleanup<br>rails db:drop db:create db:migrate<br>rails log:clear tmp:clear<br>rails about<br>rails middleware<br>rails routes | grep uers</pre><p><strong>Thanks for reading!</strong><br> If you found this helpful, consider sharing it with fellow Rails devs.<br> Feel free to bookmark this for later — and happy coding! 💻❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1abaaac41354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Dynamic Views in Rails Using Stimulus: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@giri14/building-dynamic-views-in-rails-using-stimulus-a-step-by-step-guide-9052a1271ca8?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/9052a1271ca8</guid>
            <category><![CDATA[stimulus]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[hotwire-rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 12:36:23 GMT</pubDate>
            <atom:updated>2024-10-24T12:42:52.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHkmH8a__NZrvbDwuQDXQg.jpeg" /></figure><p>When working with Rails applications, many developers prefer a clean, maintainable approach to building user interfaces. Traditionally, we might use Rails partials to manage and render UI components like lists and forms, but with the rise of front-end frameworks and JavaScript-driven behavior, combining Rails with a frontend JavaScript library has become a popular way to manage UI interactions.</p><p>In this blog, we’ll look at how you can move from a classic Rails partials approach to a more dynamic system by incorporating <strong>Stimulus</strong>, a modern JavaScript framework for adding behavior to your HTML views in an organized way.</p><p>We’ll explore how to render dynamic lists by extending the traditional approach with Stimulus, which will allow us to build out interactions more cleanly, without the complexity that often comes with larger frameworks like React or Angular. Stimulus lets you keep the flexibility of Rails’ server-rendered views while adding just enough JavaScript to manage interactivity.</p><h4>The Concepts</h4><p>Before we jump into the code, let’s first explore the key concepts involved:</p><p><strong>1.</strong> <strong>Rails Partials: The Traditional Way</strong><br>In Rails, partials are used to break views into smaller, reusable components. For example, if you have a list of items (say, a list of friends), you might render each item using a partial. Here’s what that would look like in a typical Rails view:</p><pre>&lt;h3&gt; My Friends &lt;/h3&gt;<br>&lt;ul&gt;<br> &lt;%= render partial: &quot;my_friend_item&quot;, collection: @friends %&gt;<br>&lt;/ul&gt;</pre><p>Here, we loop through the <strong>@friends</strong> collection and render a partial view <em>(_my_friend_item.html.erb)</em> for each friend. This works great for static or simple applications but has limitations when you want to add dynamic behavior — like updating the list without reloading the entire page, or adding interactive features.</p><p><strong>2. The Stimulus Framework</strong><br>Stimulus is a lightweight JavaScript framework that pairs beautifully with Rails. It’s part of the Rails ecosystem by default, and it helps you add interactivity without changing how you structure your HTML.</p><p>The core idea of Stimulus is <strong>controllers</strong> that respond to DOM events. These controllers are applied to HTML elements via <strong>data-controller</strong> attributes, and you can specify <strong>targets</strong> inside the HTML for the controller to interact with.</p><p><strong>3. Combining Partials and Stimulus</strong><br>We can use Stimulus to add JavaScript-driven behavior to our Rails partials. Instead of rendering everything at once on the server, we can render templates that can be updated dynamically via JavaScript, controlled by Stimulus.</p><p>Let’s walk through a basic example of rendering a list of friends. We’ll start by setting up the view and Stimulus controller, which will allow us to build up from a simple approach to more complex functionality.</p><p><strong>Step 1: Set Up the Rails View (ERB)</strong></p><p>The first step is to create the view where the list will appear. Instead of using a plain partial, we’ll wrap it in a Stimulus-powered component. This means we can still use the flexibility of Rails to render static content while giving us the ability to update it dynamically later.</p><p>Here’s the initial view<em> (index.html.erb)</em>:</p><pre>&lt;div data-controller=&quot;friend-list&quot;&gt;<br>  &lt;div&gt;<br>    &lt;h3&gt;My friends&lt;/h3&gt;<br>    &lt;ul id=&quot;my_friend_list&quot; data-friend-list-target=&quot;list&quot;&gt;&lt;/ul&gt;<br>  &lt;/div&gt;<br><br>  &lt;div style=&quot;display: none&quot;&gt;<br>    &lt;template id=&quot;my_friend_item_template&quot; data-friend-list-target=&quot;template&quot;&gt;<br>      &lt;li&gt;<br>        &lt;h3&gt;&lt;/h3&gt;<br>        &lt;p class=&quot;description&quot;&gt;&lt;/p&gt;<br>      &lt;/li&gt;<br>    &lt;/template&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>Explanation:</strong><br>- The <strong>div</strong> with <strong>data-controller=friend-list</strong> is the main container controlled by Stimulus. This controller will handle the rendering of the list.<br>- Inside this container, we have a <strong>ul</strong> element with the target <strong>data-friend-list-target=list</strong>.<strong> </strong>This is where the list of friends will be rendered.<br>- We also include a hidden template (template element) to define the structure of each friend item. This template will be cloned and populated with data dynamically.</p><p><strong>Step 2: Create the Stimulus Controller</strong></p><p>The next step is to create a <strong>Stimulus controller</strong> that will handle rendering the list of friends. This controller will take care of populating the <strong>ul</strong> element with items dynamically when the page loads.</p><p>Stimulus controllers are placed in the (app/javascript/controllers) directory. Let’s create a file called <em>friend_list_controller.js</em>:</p><pre>// app/javascript/controllers/friend_list_controller.js<br><br>import { Controller } from &quot;@hotwired/stimulus&quot;;<br><br>export default class extends Controller {<br>  static targets = [&quot;list&quot;, &quot;template&quot;];<br><br>  connect() {<br>    this.friends = [<br>      { name: &quot;Max&quot;, description: &quot;Loves coding.&quot; },<br>      { name: &quot;Frodo&quot;, description: &quot;Enjoys adventures.&quot; },<br>    ];<br><br>    this.renderFriends();<br>  }<br><br>  // Function to render all friends in the collection<br>  renderFriends() {<br>    this.friends.forEach((friend) =&gt; {<br>      this.addFriendToList(friend);<br>    });<br>  }<br><br>  // Method to add a single friend to the list<br>  addFriendToList(friend) {<br>    const template = this.templateTarget.content.cloneNode(true); // Clone the template<br>    template.querySelector(&quot;h3&quot;).textContent = friend.name;<br>    template.querySelector(&quot;.description&quot;).textContent = friend.description;<br><br>    this.listTarget.appendChild(template); // Append the friend to the list<br>  }<br><br>  // You can add more methods here for dynamic behavior like removing friends, etc.<br>}</pre><p><strong>Explanation:</strong><br>- <strong>static targets = [“list”, “template”]</strong>: We declare two targets here. The list target is where we’ll render our list items, and the template target is the hidden HTML template we will clone.</p><p>- <strong>connect()</strong>: This is the lifecycle method that runs when the controller is connected to the DOM. We use it to initialize the list with some static data for now (later, we can pull in real data).</p><p>- <strong>renderFriends()</strong>: This method loops through an array of friend objects and calls <strong>addFriendToList()</strong> to render each friend.</p><p>- <strong>addFriendToList(friend)</strong>: This function clones the hidden template, populates it with the friend’s name and description, and appends it to the list.</p><p><strong>What Have We Achieved So Far?</strong></p><p>By this point, we have taken the traditional Rails partial approach and enhanced it using Stimulus. We’re now dynamically rendering the list of friends directly on the client-side, but still keeping the simplicity of Rails. Stimulus is handling the interaction and rendering logic without complex configuration or heavy front-end dependencies.</p><p>This initial setup is simple but powerful. We can now easily modify, update, or remove items from the list without reloading the page, while still using Rails to handle the server-side logic and data.</p><p>In the next steps (not covered in this post), we can:<br>- Fetch dynamic data from Rails controllers or an API.<br>- Add interactivity like adding or removing friends dynamically.<br>- Extend the logic to handle more complex behavior with minimal JavaScript.</p><p>Stay tuned for Part 2, where we’ll dive deeper into these more advanced topics!</p><p><strong>Conclusion</strong></p><p>By combining Rails and Stimulus, we get the best of both worlds — maintaining the simplicity and productivity of Rails while adding just enough JavaScript to make the front-end interactive and dynamic. With Stimulus, you don’t have to rewrite your entire view layer or deal with heavy JavaScript frameworks. Instead, you can incrementally add interactivity exactly where it’s needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9052a1271ca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Using Nested Attributes in Ruby on Rails]]></title>
            <link>https://medium.com/@giri14/comprehensive-guide-to-using-nested-attributes-in-ruby-on-rails-efb3203786a9?source=rss-af9a6a770888------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb3203786a9</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[railsdevelopment]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Giritharan Elangovan]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 18:41:35 GMT</pubDate>
            <atom:updated>2024-08-05T10:55:42.966Z</atom:updated>
            <content:encoded><![CDATA[<p>In Ruby on Rails applications, managing associated records through nested attributes is a powerful feature provided by ActiveRecord. It allows you to save and update attributes on associated models through their parent model seamlessly. This guide explores everything you need to know about nested attributes, from setup to advanced customization.</p><p><strong>What are Nested Attributes?</strong></p><p>Nested attributes in ActiveRecord enable you to manipulate associated records through their parent model. By default, nested attribute updating is disabled and needs to be explicitly enabled using the accepts_nested_attributes_for class method.</p><p><strong>Setting Up Nested Attributes</strong></p><p>To illustrate, consider a Member model that has_one Avatar and has_many Posts. Here’s how you can enable nested attributes for these associations:</p><pre>class Member &lt; ActiveRecord::Base<br> has_one :avatar<br> has_many :posts<br> <br> accepts_nested_attributes_for :avatar, :posts<br>end</pre><p><strong>One-to-One Association</strong></p><p><strong>Creating and Updating Associated Records</strong></p><p>For a has_one association like Avatar, you can create and update records through nested attributes. Here’s an example:</p><pre>params = { member: { name: &#39;Jack&#39;, avatar_attributes: { icon: &#39;smiling&#39; } } }<br>member = Member.create(params[:member])<br><br># Accessing created avatar<br>member.avatar.icon # =&gt; &#39;smiling&#39;<br><br># Updating avatar through member<br>params = { member: { avatar_attributes: { id: member.avatar.id, icon: &#39;sad&#39; } } }<br>member.update(params[:member])<br><br># Accessing updated avatar<br>member.avatar.icon # =&gt; &#39;sad&#39;</pre><p><strong>Update Only Action</strong></p><p>If you want to update the current avatar without providing the ID, use the update_only option:</p><pre>class Member &lt; ActiveRecord::Base<br> has_one :avatar<br> accepts_nested_attributes_for :avatar, update_only: true<br>end</pre><p><strong>One-to-Many Association</strong></p><p>For a has_many association like Post, nested attributes allow you to set or update attributes on multiple associated records. Here’s an example:</p><pre>params = { member: {<br> name: &#39;joe&#39;, posts_attributes: [<br> { title: &#39;Kari, the awesome Ruby documentation browser!&#39; },<br> { title: &#39;The egalitarian assumption of the modern citizen&#39; },<br> { title: &#39;&#39;, _destroy: &#39;1&#39; } # this will be ignored<br> ]<br>}}<br><br>member = Member.create(params[:member])<br><br># Accessing created posts<br>member.posts.length # =&gt; 2<br>member.posts.first.title # =&gt; &#39;Kari, the awesome Ruby documentation browser!&#39;<br>member.posts.second.title # =&gt; &#39;The egalitarian assumption of the modern citizen&#39;</pre><p><strong>Advanced Options</strong></p><p><strong>Reject If</strong></p><p>You can use reject_if to ignore new record hashes based on conditions:</p><pre>class Member &lt; ActiveRecord::Base<br> has_many :posts<br> accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes[&#39;title&#39;].blank? }<br>end</pre><p><strong>Custom Rejection Method</strong></p><p>Alternatively, define a method for reject_if:</p><pre>class Member &lt; ActiveRecord::Base<br> has_many :posts<br> accepts_nested_attributes_for :posts, reject_if: :reject_posts<br>def reject_posts(attributes)<br> attributes[&#39;title&#39;].blank?<br> end<br>end</pre><p><strong>Destroying Associated Records</strong></p><p>To enable destruction of associated records via _destroy key:</p><pre>class Member &lt; ActiveRecord::Base<br> has_many :posts<br> accepts_nested_attributes_for :posts, allow_destroy: true<br>end</pre><p><strong>Form Integration</strong></p><p><strong>Using </strong><strong>fields_for</strong></p><p>When creating forms for nested attributes, use fields_for in Rails views:</p><pre>&lt;%= form_with(model: @member) do |form| %&gt;<br> &lt;%= form.label :name %&gt;<br> &lt;%= form.text_field :name %&gt;<br> <br> &lt;%= form.fields_for :posts do |post_form| %&gt;<br> &lt;%= post_form.label :title %&gt;<br> &lt;%= post_form.text_field :title %&gt;<br> &lt;% end %&gt;<br> <br> &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p><strong>Validating the Presence of Parent Model</strong></p><p>By default, belongs_to association validates the presence of the parent model. Disable this behavior using optional: true:</p><pre>class Patient &lt; ActiveRecord::Base<br> belongs_to :veterinarian, optional: true<br> validates :veterinarian, presence: true, unless: -&gt; { awaiting_intake }<br>end</pre><p><strong>Conclusion</strong></p><p>In conclusion, nested attributes in Ruby on Rails provide a convenient way to manage associated records through their parent models. Whether it’s one-to-one or one-to-many associations, understanding and utilizing these features effectively can greatly simplify your application’s data management and form handling. By leveraging options like reject_if, allow_destroy, and custom method overrides, you can tailor nested attributes to suit your application’s specific needs. Integrating nested attributes into your forms using fields_for ensures a seamless user experience when dealing with complex data structures. Mastering nested attributes empowers Rails developers to build robust and maintainable applications with ease.</p><p>This comprehensive guide aims to equip you with the knowledge and examples needed to leverage nested attributes effectively in your Ruby on Rails projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb3203786a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>