<?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 Yunus Bulut on Medium]]></title>
        <description><![CDATA[Stories by Yunus Bulut on Medium]]></description>
        <link>https://medium.com/@yunusbulutt?source=rss-af505edf7799------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AAkRDPCWNE7w8zSyNNywCg@2x.jpeg</url>
            <title>Stories by Yunus Bulut on Medium</title>
            <link>https://medium.com/@yunusbulutt?source=rss-af505edf7799------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:33:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yunusbulutt/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[Performance Optimization for Rails Applications]]></title>
            <link>https://blog.simprasuite.com/performance-optimization-for-rails-applications-a30fadfd554f?source=rss-af505edf7799------2</link>
            <guid isPermaLink="false">https://medium.com/p/a30fadfd554f</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[database-optimization]]></category>
            <category><![CDATA[memory-optimization]]></category>
            <dc:creator><![CDATA[Yunus Bulut]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 14:39:59 GMT</pubDate>
            <atom:updated>2024-10-08T14:39:59.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*eDHejbtZJrw57OJ-.jpg" /></figure><p>Rails framework is known for its simplicity and productivity, allowing developers to create applications quickly. However, as the complexity of applications and the user base grow, performance issues may arise. This article will guide you through various strategies and best practices to optimize the performance of your Rails applications.</p><h3>Database Optimization</h3><p>The database is often the most significant performance bottleneck in a Rails application. Poorly designed queries, lack of indexing, or even improper caching can slow down the application significantly. Optimizing your database can significantly improve the speed and efficiency of your application. Here are some common issues to consider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*VaPzNE7KBH8AsyO7" /></figure><h4>Indexing Strategies</h4><p>Indexes offer rapid access to records in database tables, significantly enhancing query performance. However, maintaining an index can introduce additional costs during database updates, necessitating a careful balance.</p><p>Indexes are typically created on frequently queried, sorted, or grouped columns. This is especially beneficial in large datasets, as it can substantially reduce query times and improve user experience. Different types of indexing strategies include simple indexes, composite indexes, partial indexes, and full-text indexes. Each strategy is optimized for different usage scenarios and data structures.</p><p>For instance, in an e-commerce application, users frequently query their orders. These queries often involve the user_id, order_date, and status columns. To enable users to quickly find their orders from a specific date, creating a composite index is crucial.</p><p>To implement this, we can use the following migration code:</p><pre>class AddCompositeIndexToOrders &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    add_index :orders, [:user_id, :order_date, :status], name: &#39;index_orders_on_user_id_order_date_status&#39;<br>  end<br>end</pre><p>With this composite index in place, when users want to query their completed orders from January 1, 2024, they can use the following query:</p><pre>Order.where(user_id: 123)<br>     .where(order_date: &#39;2024-01-01&#39;)<br>     .where(status: &#39;completed&#39;)<br>     .order(order_date: :desc)</pre><p>This query benefits from the composite index, allowing the database to directly access the user_id, order_date, and status columns, thus significantly reducing query execution time.</p><p>Another important indexing strategy is the use of partial indexes. For example, in a social media platform, we track users’ active status. However, since we only query active users, it makes sense to create a partial index for users where the active column is set to true.</p><p>The migration code for this partial index could look like this:</p><pre>class AddPartialIndexToUsers &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    add_index :users, [:last_login_at, :email], where: &quot;active = true&quot;, name: &#39;index_active_users_on_last_login_and_email&#39;<br>  end<br>end</pre><p>This partial index applies only to users with an active status of true. To list the recently logged-in active users in the admin panel, we can execute this query:</p><pre>User.where(active: true)<br>    .where.not(last_login_at: nil)<br>    .order(last_login_at: :desc)</pre><p>This query specifically targets users with an active status of true, leveraging the index on last_login_at to enhance performance.</p><p>Lastly, full-text indexes are utilized for quickly searching large article content. In a blogging platform, we want to perform text searches within the content field. By using a full-text index, we can efficiently scan through large articles. For instance, with PostgreSQL, we can create a GIN index for full-text searching.</p><p>The migration code for setting up this index might look like this:</p><pre>class AddFullTextIndexToArticles &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    add_index :articles, :content, using: :gin, opclass: :gin_trgm_ops<br>  end<br>end</pre><p>When users want to search for articles containing the phrase. optimizing queries they can run the following query:</p><pre>Article.where(&quot;content ILIKE ?&quot;, &quot;%optimizing queries%&quot;)</pre><p>This query utilizes the full-text search capabilities provided by the gin_trgm_ops index, allowing for quick text searches in article content. In large datasets, query execution times can significantly decrease.</p><h4>N+1 Query Problem</h4><p>The N+1 query problem occurs in a database application when related data is fetched through separate queries after the main query. This problem typically arises when querying a main object along with its associated objects, resulting in one query for the main object and additional queries for each related object. This situation leads to an unnecessary increase in the total number of queries and, consequently, a decrease in application performance.</p><p>Let’s consider an e-commerce application where we want to list the reviews for each product. The following code illustrates the N+1 query problem:</p><pre>products = Product.all<br>products.each do |product|<br>  puts &quot;#{product.name} has #{product.reviews.size} reviews.&quot;<br>end</pre><p>In this example, the Product.all query retrieves all products. However, the product.reviews.size statement sends a separate query for each product. For instance, if there are 10 products, a total of 11 queries are executed (1 main query + 10 sub-queries). This situation imposes an unnecessary load on the database and can cause the application to run slowly.</p><p>To solve the N+1 query problem, we can use Rails’ eager loading feature. Eager loading allows us to fetch related data with a single query. Here’s the code that addresses this issue:</p><pre>products = Product.includes(:reviews).all<br>products.each do |product|<br>  puts &quot;#{product.name} has #{product.reviews.size} reviews.&quot;<br>end</pre><p>In this code, the Product.includes(:reviews).all statement retrieves both products and their associated reviews in a single query. This results in only one query being executed, reducing the load on the database and enhancing the application&#39;s performance.</p><p>You can refer to the article I previously wrote for more detailed information: <a href="https://medium.com/wereprotein/understanding-and-solving-n-1-queries-in-ruby-on-rails-98a0b25160b">Understanding and Solving N+1 Queries in Ruby on Rails</a></p><h4>Caching</h4><p>Pages and queries are slow because data is repeatedly fetched from the database without caching. Use caching to store commonly accessed data in memory for fast retrieval.</p><p>Caching a list of frequently accessed posts:</p><pre>def index<br>  @posts = Rails.cache.fetch(&#39;posts&#39;, expires_in: 12.hours) do<br>    Post.published.limit(10).to_a<br>  end<br>end</pre><p>Here, the Rails.cache.fetch method stores the result of the query for 12 hours, reducing the number of database queries.</p><h4>Background Jobs</h4><p>Certain database operations (e.g., data imports, batch updates) are too time-consuming to run synchronously, potentially causing request timeouts or blocking user interaction.</p><p>Offload these operations to background jobs using tools like Sidekiq or ActiveJob.</p><p>For more complex tasks such as bulk data imports from CSV files, you can use a background job to process each row asynchronously while reporting progress to the user.</p><pre>class ImportCustomersJob &lt; ApplicationJob<br>  queue_as :default<br><br>  def perform(import_id)<br>     import = Import.find(import_id)<br><br>     CustomersImporter.new(import).execute<br>  end<br>end</pre><p>In this case, the job can handle thousands of records in the background without affecting the responsiveness of the application.</p><h4>Pagination</h4><p>Pagination is a technique used to make large datasets more manageable by grouping data into specific page numbers, allowing users to view only a portion of the data at a time. This enhances the user experience and improves application performance, as only the necessary data for each page is loaded.</p><p>In web frameworks like Ruby on Rails, pagination is typically implemented using third-party libraries such as kaminari or will_paginate. These libraries provide an easy way to paginate data and automatically generate pagination links. However, pagination can also be manually implemented using SQL queries, giving developers greater control and customization options.</p><h4><strong>Use Replica DB</strong></h4><p>When your application scales, your single database server might become a bottleneck due to the increasing number of read operations. In this case, Use read replicas to distribute the load. A read replica is a copy of the primary database that can handle read traffic. This can greatly increase the performance of your Rails application. You can easily configure ActiveRecord to direct read queries to the replica.</p><pre>production:<br>  primary:<br>    adapter: postgresql<br>    database: my_primary_database<br>  replica:<br>    adapter: postgresql<br>    database: my_replica_database<br>    replica: true</pre><p>There are even more advanced strategies like Sharding, Denormalization etc. They are outside the scope of this post.</p><h3>Memory Optimization</h3><p>Memory optimization is a critical aspect of software development, particularly for applications that require efficient resource management, such as APIs. It involves strategies aimed at reducing memory consumption and improving performance by using techniques like choosing appropriate data structures, minimizing object creation, and leveraging lightweight alternatives like symbols.</p><p>By ensuring that memory usage is kept to a minimum, developers can enhance application responsiveness, reduce latency, and improve overall system efficiency. Implementing effective memory optimization practices not only benefits the application’s performance but also leads to a more sustainable use of server resources, ultimately resulting in a better user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*UQOMP9z3Et30rIHY" /></figure><h4>Use of Symbols</h4><p>In Ruby, symbols are lightweight, immutable strings that can save memory when used as keys in hashes or for other repetitive string purposes. Unlike strings, which can take up more memory with each instance, symbols are stored only once in memory. This can lead to significant memory savings, especially when dealing with large datasets or high-frequency operations.</p><p>Instead of using strings as keys in a hash or repeatedly creating the same string, use symbols to optimize memory usage.</p><pre># Inefficient: Using strings as keys<br><br>user_data = {<br>  &quot;name&quot; =&gt; &quot;John Doe&quot;,<br>  &quot;age&quot; =&gt; 30,<br>  &quot;city&quot; =&gt; &quot;New York&quot;<br>}</pre><pre># Optimized: Using symbols as keys<br><br>user_data = {<br>  name: &quot;John Doe&quot;,<br>  age: 30,<br>  city: &quot;New York&quot;<br>}<br><br>puts user_data[:name]</pre><p>Using symbols instead of strings not only conserves memory but also improves performance since symbol lookups are faster than string lookups due to their immutability.</p><h4>Large Payloads</h4><p>Carrying unnecessary data payloads in API responses increases memory consumption. It’s essential to send only the data that is required to reduce memory usage.</p><p>Instead of including unnecessary fields in the API response, the response should only contain the data needed by the client.</p><pre># Response including unnecessary data<br>render json: { users: User.all }<br><br># Response containing only necessary data<br>render json: { users: User.select(:id, :name).all }</pre><h4>Use of Memoization</h4><p>Memoization allows for an operation to be performed only once while storing the result. This prevents unnecessary repetitions and optimizes memory usage.</p><p>Instead of recalculating a computation or data retrieval operation each time it is called, it is done once and the result is stored.</p><pre># Recalculating each time<br>def result<br>  calculate_heavy_operation<br>end<br><br># Optimized: Using memoization<br>def result<br>  @result ||= calculate_heavy_operation<br>end</pre><h3><strong>Code and Algorithm Optimization</strong></h3><p>Optimizing your code and algorithms is essential to enhance the performance and scalability of Rails applications. Efficient algorithms and clean code not only improve execution speed but also reduce memory consumption and enhance the overall user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*YwJBto9HFRKxPRuw" /></figure><h4>Using Pluck</h4><p>Fetching large amounts of data from the database can cause performance issues, especially if you only need a subset of columns. Using pluck allows you to retrieve only the necessary columns, reducing both memory usage and query time.</p><p>Instead of loading entire records when you only need specific columns, use pluck to fetch only the required data.</p><pre># Inefficient: Loading entire records into memory<br>User.all.each do |user|<br>  puts user.name<br>end<br><br># Optimized: Using `pluck` to retrieve only the name column<br>User.pluck(:name).each do |user_name|<br>  puts user_name<br>end</pre><h4>Optimize Nested Loops</h4><p>Nested loops can lead to high time complexity, especially when iterating over large datasets. If two datasets need to be compared, a more efficient solution is to use a hash for fast lookups instead of repeatedly scanning through an array.</p><p>Suppose you have two arrays, one containing user records and another containing user orders. Instead of using a nested loop to check orders for each user, you can use a hash for faster lookups.</p><pre># Inefficient: Nested loop to find orders for each user<br>users.each do |user|<br>  orders.each do |order|<br>    if order.user_id == user.id<br>      user.add_order(order)<br>    end<br>  end<br>end<br><br># Optimized: Using a hash to look up orders by user_id<br>order_lookup = orders.group_by(&amp;:user_id)<br><br>users.each do |user|<br>  user_orders = order_lookup[user.id] || []<br>  user.add_orders(user_orders)<br>end</pre><p>By grouping orders by user_id into a hash first, you eliminate the need for a nested loop, making lookups faster and reducing the overall complexity.</p><h4>Bulk Inserts</h4><p>When inserting multiple records into the database, performing individual inserts can slow down performance significantly. Using bulk inserts, where multiple records are inserted in a single query, minimizes database overhead and accelerates the process.</p><p>Let’s say you are importing a large number of users. Instead of inserting each user one by one, which can result in many database transactions, you can use a bulk insert method to improve performance.</p><pre># Inefficient: Inserting records one by one<br>users.each do |user|<br>  User.create(user)<br>end<br><br># Optimized: Using bulk insert to minimize database transactions<br>User.insert_all(users)</pre><p>In the optimized version, insert_all reduces the number of database queries by inserting all the records in a single query, significantly improving performance, especially with large datasets.</p><h4>Minimize Method Calls</h4><p>Each method call in Ruby has a performance cost, especially when called within loops or frequently used blocks. Reducing unnecessary method calls, especially for built-in methods, can yield significant performance improvements. By inlining small calculations or avoiding method calls in tight loops, you reduce overhead and improve execution speed.</p><p>Suppose you are iterating over a large list of products and calling a method that formats the price each time.</p><pre># Inefficient: Calling a method inside a loop<br>products.each do |product|<br>  puts product.format_price # Method call inside loop<br>end<br><br># Optimized: Precompute outside the loop<br>formatted_prices = products.map(&amp;:format_price) # Compute once<br>formatted_prices.each { |price| puts price } # Use computed values</pre><h4>Optimize Array Operations</h4><p>Array operations can be optimized by choosing more efficient enumeration methods. In some cases, using each_with_object instead of each or map can improve performance by reducing the number of intermediate arrays created. This approach allows you to accumulate results directly into an object, minimizing memory usage and speeding up array processing.</p><p>Suppose you are creating a hash that groups orders by customer from an array of orders.</p><pre># Inefficient: Using each and pushing into a hash<br>grouped_orders = {}<br>orders.each do |order|<br>  grouped_orders[order.customer_id] ||= []<br>  grouped_orders[order.customer_id] &lt;&lt; order<br>end<br><br># Optimized: Using each_with_object for direct accumulation<br>grouped_orders = orders.each_with_object({}) do |order, result|<br>  result[order.customer_id] ||= []<br>  result[order.customer_id] &lt;&lt; order<br>end</pre><p>Using each_with_object eliminates the need for manually creating and pushing into a hash. This method is not only more efficient but also leads to cleaner and more concise code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pEvgzGjNrjHShi58.jpeg" /></figure><p>These strategies, when applied effectively, can greatly improve the performance of your Rails applications by reducing unnecessary computations, avoiding redundant object creation, and optimizing database queries.</p><h3>Conclusion</h3><p>Optimizing a Rails application requires attention to multiple aspects, from database queries to memory management and efficient code structure. By implementing these techniques, you can significantly improve the performance and scalability of your application, providing a smoother experience for users and better resource utilization. Performance optimization is an ongoing process that evolves as your application grows.</p><p>It is important to test different methods and evaluate their performance in your specific use case to determine the best solution.</p><p>I hope you enjoyed reading. ✌️ Please let me know if there is any inaccuracies in the information provided. 💎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*uiHI876atQJGInvxfdF6BQ.gif" /></figure><h4>References</h4><ul><li><a href="https://reintech.io/blog/how-to-optimize-a-ruby-on-rails-application#google_vignette">How to Optimize a Ruby on Rails Application</a></li><li><a href="https://dev.to/haseebeqx/notes-on-performance-optimization-in-rails-applications-36cg">Notes on Performance Optimization in Rails Applications</a></li><li><a href="https://medium.com/@salujabhavesh/optimizing-performance-in-ruby-on-rails-applications-98f34848bd34">Optimizing Performance in Ruby on Rails Applications</a></li><li><a href="https://evilmartians.com/chronicles/test-prof-3-guided-and-automated-ruby-test-profiling">TestProf III: guided and automated Ruby test profiling-Martian Chronicles, Evil Martians&#39; team blog</a></li></ul><ul><li><a href="https://pawelurbanek.com/optimize-rails-performance">My Recipe for Optimizing Performance of Rails Applications</a></li><li><a href="https://reintech.io/blog/how-to-optimize-a-ruby-on-rails-application#google_vignette">How to Optimize a Ruby on Rails Application</a></li><li><a href="https://sloboda-studio.com/blog/how-to-improve-ruby-on-rails-app-performance/">Optimizing Performance of Rails Applications</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a30fadfd554f" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/performance-optimization-for-rails-applications-a30fadfd554f">Performance Optimization for Rails Applications</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Solving N+1 Queries in Ruby on Rails]]></title>
            <link>https://blog.simprasuite.com/understanding-and-solving-n-1-queries-in-ruby-on-rails-98a0b25160b?source=rss-af505edf7799------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a0b25160b</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[n-plus-1-queries]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Yunus Bulut]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 07:12:01 GMT</pubDate>
            <atom:updated>2023-04-25T07:12:01.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*662iUkjenyDZoiTh.jpg" /><figcaption>The train represents the database. The people on top of the train represent each additional SQL query :)</figcaption></figure><h4>Introduction</h4><p>In Ruby on Rails, the Active Record Object-Relational Mapping (ORM) library is used to interact with databases. While it abstracts away many of the complexities of SQL, it can still lead to performance issues when working with large datasets. One common problem is N+1 queries, which occur when your application makes multiple database queries to retrieve associated data for a set of records. In this post, we will explore what N+1 queries are, why they happen, and how to solve them with SQL and ORM examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AthHjyt1s3tkWhYzJ1uzbQ.png" /><figcaption>N+1 Query Problem Burn Database, Photo Source:<a href="https://t.ly/JV0S"> https://t.ly/JV0S</a></figcaption></figure><h4>Let’s Understand The Problem</h4><p>N+1 queries occur when your application makes multiple database queries to retrieve associated data for a set of records. Here is an example of a simple Rails controller action that retrieves all products and their associated comments:</p><pre># app/model/product.rb<br><br>class Product &lt; ApplicationRecord<br>  has_many :comments<br>end</pre><pre># app/model/user.rb<br><br>class User &lt; ApplicationRecord<br>  has_many :comments<br>end</pre><pre># app/model/comments.rb<br><br>class Comment &lt; ApplicationRecord<br>  belongs_to :product<br>  belongs_to :user<br>end</pre><pre># app/controllers/products_controller.rb<br><br>class ProductsController &lt; ApplicationController<br>  def index<br>    @products = Product.all<br>  end<br>end</pre><p>And in the view file, you are displaying all the product’s names, and the comments count</p><pre># app/views/products/index.html.erb<br><br>&lt;table&gt;<br>  &lt;tbody&gt;<br>    &lt;% @products.each do |product| %&gt;<br>      &lt;tr&gt;<br>        &lt;td&gt;&lt;%= product.name %&gt;&lt;/td&gt;<br>        &lt;td&gt;&lt;%= product.comments.count %&gt;&lt;/td&gt;<br>        &lt;% product.comments.each do |comment| %&gt;<br>          &lt;td&gt;&lt;%= comment.user.name %&gt;&lt;/td&gt;<br>          &lt;td&gt;&lt;%= comment.body %&gt;&lt;/td&gt;<br>        &lt;% end %&gt;<br>      &lt;/tr&gt;<br>   &lt;% end %&gt;<br>  &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>Without proper optimization, this action will make one query to retrieve all products, and then make an additional query for each product to retrieve their associated comments count. This can lead to slow performance and high database load, especially when dealing with large datasets.</p><p>The above code works, but it makes far too many independent database queries:</p><pre>SELECT * FROM products;<br>SELECT COUNT(*) FROM comments WHERE product_id = 1;<br>SELECT COUNT(*) FROM comments WHERE product_id = 2;<br>SELECT COUNT(*) FROM comments WHERE product_id = 3;<br>...</pre><h4>Solution</h4><p>There are several ways to solve N+1 queries in Ruby on Rails, some of the most common include:</p><ul><li><strong>Using includes:</strong> includes method allows you to load associated data in a single query, instead of making separate queries for each record. For example, instead of making a separate query for each product&#39;s comments, you can use the includes method to load all comments in a single query.</li></ul><pre># app/controllers/products_controller.rb<br><br>class ProductsController &lt; ApplicationController<br>  def index<br>    @products = Product.all.includes(:comments)<br>  end<br>end</pre><pre># app/views/products/index.html.erb<br><br>&lt;table&gt;<br>  &lt;tbody&gt;<br>    &lt;% @products.each do |product| %&gt;<br>      &lt;tr&gt;<br>        &lt;td&gt;&lt;%= product.name %&gt;&lt;/td&gt;<br>        &lt;td&gt;&lt;%= product.comment.size %&gt;&lt;/td&gt;<br>        &lt;% product.comments.each do |comment| %&gt;<br>          &lt;td&gt;&lt;%= comment.body %&gt;&lt;/td&gt;<br>        &lt;% end %&gt;<br>     &lt;/tr&gt;<br>   &lt;% end %&gt;<br>  &lt;/tbody&gt;<br>&lt;/table&gt;</pre><pre>SELECT * FROM products;<br>SELECT * FROM comments WHERE product_id IN (1, 2, 3 ...);</pre><ul><li><strong>Goldiloader Gem: </strong>The Goldiloader gem is used to improve database loading performance in Ruby on Rails applications. This gem caches database queries and prevents duplicate queries in order to increase database loading performance. Additionally, the Goldiloader gem automatically handles caching and reloading of database queries.</li></ul><blockquote>Wouldn’t it be awesome if ActiveRecord didn’t make you think about eager loading and it just did the “right” thing by default? With Goldiloader it can!</blockquote><pre># Gemfile<br><br>gem &#39;goldiloader&#39;</pre><p>Here are some sample queries without the Goldiloader:</p><pre>&gt; products = Product.limit(5).to_a<br><br># SELECT * FROM products LIMIT 5</pre><pre>&gt; products.each { |product| product.comments.to_a }<br><br># SELECT * FROM comments WHERE product_id = 1<br># SELECT * FROM comments WHERE product_id = 2<br># SELECT * FROM comments WHERE product_id = 3<br># SELECT * FROM comments WHERE product_id = 4<br># SELECT * FROM comments WHERE product_id = 5</pre><p>Here are the same queries with the Goldiloader:</p><pre>&gt; products = Product.limit(5).to_a<br><br># SELECT * FROM blogs LIMIT 5</pre><pre>&gt; products.each { |product| product.comments.to_a }<br><br># SELECT * FROM comments WHERE product_id IN (1,2,3,4,5)</pre><blockquote>Whoa! It automatically loaded all of the posts for our five blogs in a single database query without specifying any eager loads! Goldiloader assumes that you’ll access all models loaded from a query in a uniform way. The first time you traverse an association on any of the models it will eager load the association for all the models. It even works with arbitrary nesting of associations.</blockquote><p>For usage instructions, visit: <a href="https://github.com/salsify/goldiloader">https://github.com/salsify/goldiloader</a></p><ul><li><strong>Bullet Gem:</strong> Bullet is a gem that helps you to detect N+1 queries and other performance issues in your application. You can use it to identify the N+1 queries in your application, and then use the solutions discussed above to optimize your queries.</li></ul><pre># Gemfile<br><br>gem &#39;bullet&#39;, group: &#39;development&#39;</pre><pre># config/environments/development.rb<br><br>config.after_initialize do<br>  Bullet.enable = true<br>  Bullet.alert = true<br>  Bullet.bullet_logger = true<br>  Bullet.console = true<br>end</pre><pre># spec/spec_helper.rb<br><br>RSpec.configure do |config|<br>  if Bullet.enable?<br>    config.before(:each) { Bullet.start_request }<br>    config.after(:each)  { Bullet.end_request }<br>  end<br>end</pre><ul><li>Despite all your efforts to eliminate N+1 queries from your application by carefully reviewing your code, it is still possible for errors to slip into your production code. This is where the Bullet Gem comes in as an invaluable tool, by automating the process of identifying and resolving these performance issues, it ensures that your application runs smoothly and efficiently in production.</li></ul><blockquote>The Bullet gem is designed to help you increase your application’s performance by reducing the number of queries it makes. It will watch your queries while you develop your application and notify you when you should add eager loading (N+1 queries), when you’re using eager loading that isn’t necessary and when you should use counter cache.</blockquote><p>For usage instructions, visit: <a href="https://github.com/flyerhzm/bullet">https://github.com/flyerhzm/bullet</a></p><h4>GraphQL</h4><p>GraphQL is a query language for modern web apps that lets client apps request only the data they need, improving performance. Ruby developers can use it with web app frameworks to build apps and easily fetch data from databases or external APIs.</p><ul><li><strong>Graphql Batch Gem:</strong> The <a href="https://github.com/Shopify/graphql-batch"><strong>graphql-batch</strong></a> gem is a library for the Ruby on Rails framework that allows batch loading of multiple records from a GraphQL API. It is used to reduce the number of requests made to the server by loading multiple records with a single request.</li><li>This can improve the performance of a Rails application that makes heavy use of GraphQL. The gem is compatible with the <a href="https://graphql-ruby.org/"><strong>graphql-ruby</strong></a> gem, which is a Ruby implementation of the GraphQL specification.</li></ul><pre># Gemfile<br><br>gem &#39;graphql&#39;<br>gem &#39;graphql-batch&#39;</pre><pre><br># app/graphql/loaders/record_loader.rb<br><br>class RecordLoader &lt; GraphQL::Batch::Loader<br>  def initialize(model)<br>    @model = model<br>  end<br><br>  def perform(ids)<br>    @model.where(id: ids).each { |record| fulfill(record.id, record) }<br>    ids.each { |id| fulfill(id, nil) unless fulfilled?(id) }<br>  end<br>end<br></pre><pre># app/graphql/types/comment_type.rb<br><br>field :product, Types::Product, null: true <br><br>def product<br>  RecordLoader.for(Product).load(object.product_id)<br>end</pre><p>For usage instructions, visit: <a href="https://github.com/Shopify/graphql-batch">https://github.com/Shopify/graphql-batch</a></p><h4>In Conclusion 💎</h4><p>N+1 queries in Ruby on Rails can lead to slow performance and high database load, especially when working with large datasets. However, by using techniques such as includes and even using a gem like bullet, you can optimize your application&#39;s database queries and improve performance.</p><p>It is important to test different methods and evaluate their performance in your specific use case to determine the best solution.</p><p>Please let me know if there is any inaccuracies in the information provided. I hope this article has been helpful. ✌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*e6_21BCsV0p5_f1pgrjIWg.gif" /><figcaption>Finally, Database happy, SQL queries happy, Developer happy :)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a0b25160b" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/understanding-and-solving-n-1-queries-in-ruby-on-rails-98a0b25160b">Understanding and Solving N+1 Queries in Ruby on Rails</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Polymorphic Associations in Ruby on Rails ?]]></title>
            <link>https://blog.simprasuite.com/how-to-use-polymorphic-associations-in-ruby-on-rails-d234a066f3cb?source=rss-af505edf7799------2</link>
            <guid isPermaLink="false">https://medium.com/p/d234a066f3cb</guid>
            <category><![CDATA[polymorphic-association]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Yunus Bulut]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 14:07:06 GMT</pubDate>
            <atom:updated>2022-12-16T14:07:06.912Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Polymorphic Associations in Ruby on Rails?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocYgpJY9doIFupZPNbVkIw.png" /></figure><h3><strong>Introduction</strong></h3><p>In Ruby on Rails, a polymorphic association allows a model to belong to more than one other model on a single association. This can be useful in situations where you want to associate a single model with multiple types of models, without having to create separate associations for each type.</p><h3><strong>The Problem</strong></h3><p>Consider the following scenario: you are building a social media application and you want to create a <strong>`Like`</strong> feature that allows users to like posts and comments.</p><p>In a traditional one-to-many association, you would need to create separate models for each type of <strong><em>`likeable`</em></strong> object (e.g., PostLike, CommentLike), and each model would have a foreign key pointing to the corresponding <strong><em>`likeable`</em></strong> object. This can get messy and difficult to maintain, especially as your application grows in complexity.</p><p>The problem with using multiple join tables to model many-to-many relationships is that it can become difficult to query and update the data. You may need to write complex SQL queries to retrieve the data you need, or use multiple Active Record associations to traverse the relationships. This can be time-consuming and error-prone, especially if you have multiple levels of relationships between models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SRENWf_29V3iPU12E9YK7Q.jpeg" /></figure><h3><strong>The Solution</strong></h3><p>To solve this problem, we can use polymorphic associations in Ruby on Rails. This allows us to define a single association that can belong to multiple models, without having to write extra code to handle the different types of content.</p><p>Here is how to set up a polymorphic association in Rails:</p><ul><li>Add a likeable_id and a likeable_type column to the likes table. These columns will be used to store the ID and type of the content that is being liked.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd381ccb5cadbe301f4b9f1a7f8f4ae1/href">https://medium.com/media/cd381ccb5cadbe301f4b9f1a7f8f4ae1/href</a></iframe><ul><li>Define a polymorphic association in the Like model by using the belongs_to method, and passing the :likeable option. This tells Rails that the Like model can belong to any model that is specified as the value of the :likeable option.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7410cda4cf3d5e982c5ee8ac403ee36/href">https://medium.com/media/d7410cda4cf3d5e982c5ee8ac403ee36/href</a></iframe><ul><li>In the models for the different types of content that can be liked (e.g. Post and Comment), define a reverse association by using the has_many method and passing the :likes option. This allows us to access the likes for a particular piece of content.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5d9fd648649739de2d4fb08534c138/href">https://medium.com/media/ed5d9fd648649739de2d4fb08534c138/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41b898f7357412f0a46606f3919f08c2/href">https://medium.com/media/41b898f7357412f0a46606f3919f08c2/href</a></iframe><p>With this in place, we can now associate a <strong>Like</strong> with either a <strong>Post</strong> or a <strong>Comment</strong>, using a single association. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1361e6ac2d777f79c7bba3fa50e7d94a/href">https://medium.com/media/1361e6ac2d777f79c7bba3fa50e7d94a/href</a></iframe><h3><strong>Conclusion</strong></h3><p>Polymorphic associations in Ruby on Rails can be a powerful tool for simplifying many-to-many relationships between models. By using a single association, you can avoid the complexity and maintenance issues of multiple join tables. This can make it easier to query and update your data, and can help you build more flexible and scalable applications.</p><p>The polymorphic association allows you to easily add comments to any model that you want, without having to define separate associations for each model. This can make your code more DRY (don’t repeat yourself) and easier to maintain.</p><p>By using the steps outlined above, you can easily set up polymorphic associations in your own Rails application and start taking advantage of the benefits they offer.</p><p>In conclusion, polymorphic associations are a powerful and flexible way to handle complex model relationships in Ruby on Rails.</p><p>I hope you enjoyed reading. ✌️ I wish you happy coding. 👨‍💻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*W-K10kAi2dOxXtdVHjsSHw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d234a066f3cb" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/how-to-use-polymorphic-associations-in-ruby-on-rails-d234a066f3cb">How to use Polymorphic Associations in Ruby on Rails ?</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>