author avatar

nitturu.baba

Tue Oct 29 2024

To avoid N+1 queries in Rails, you can use the .includes method to eager-load associated records, which reduces the number of database calls.

Suppose you have two models: Order and Item, where an Order has many Items. Without eager-loading, querying each order’s items individually would lead to N+1 queries.



orders = Order.all 
orders.each do |order| 
  puts order.items # Each order triggers a separate query for items
end


By using .includes, Rails will fetch all associated items in a single additional query:



orders = Order.includes(:items)
orders.each do |order|
  puts order.items # No extra query is triggered here
end


This approach loads Order records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.

#CU6U0R822
author avatar

nitturu.baba

Mon Oct 28 2024

before_action runs a specified method before the controller action. It’s useful for tasks that need to happen before executing the main action, such as authentication, setting up a resource, or ensuring permissions.


after_action runs a specified method after the controller action has executed. It’s useful for tasks that need to happen after the response is rendered, such as logging activity, tracking metrics, or cleaning up resources.




class PointsController < ApplicationController
  before_action :set_user_points, only: [:show, :redeem]
  after_action :update_points_history, only: [:redeem]

  def show
    # Show points balance
  end

  def redeem
    # Redeem points logic
  end

  private

  def set_user_points
    @points = current_user.points
  end

  def update_points_history
    # Log the points redemption action
  end
end



In the above example set_user_points will execute before the controller actions show and redeem. update_points_history will execute after the redeem action.

#CU6U0R822
author avatar

ayasha.pandey

Fri Oct 25 2024

onDelete: Cascade in Prisma automatically deletes the child records when a parent record is deleted.




model User {
  id    Int     @id @default(autoincrement())
  posts Post[]
}

model Post {
  id     Int   @id @default(autoincrement())
  userId Int
  user   User  @relation(fields: [userId], references: [id], onDelete: Cascade)
}


Now when you delete a user:


await prisma.user.delete({ where: { id: 123 } })


All their posts are automatically deleted too!

#prisma #schema
author avatar

nived.hari

Fri Oct 25 2024

Combining Commits with Git Squash
Squashing commits allows us to combine multiple related commits into a single one, helping to keep the commit history clean.

Let's say if we want to combine 3 separate commits which are related to same thing into one clean commit,

1. Checkout the branch


git checkout branch-name


2. Run the following command


git rebase -i HEAD~3


3. Modify the rebase file. Git will open a text window with last 3 commits


pick 7f9d4bf first commit
pick 3f8e810 second commit
pick ec48d74 third commit


pick means to keep the commit as is.
• To squash the second and third commits into the first one, change pick to squash / s for those commits.
4. After we save and exit, another text editor will pop-up with commit messages


# This is a combination of 3 commits.
# The first commit message:

fix for bug

# Commit message for #2:
Updated this

# Commit message for #3:
Added comments & updated README


Simply saving this will result in a single commit with a commit message that is a concatination of all 3 messages.
We can choose which one we want, or we can create a new message entirely.
5. Complete the Rebase
After saving, we now have a single commit representing the previous three.

#git #rebase
author avatar

nived.hari

Thu Oct 24 2024

Concerns
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern module provided by Rails.
They help in organizing and reusing code across controllers and models by extracting common functionality into modules.


There are 2 main blocks in a concern

1. included

1. Any code inside this block is evaluated in the context of the including class.
2. if sample class includes a concern, anything inside the included block will be evaluated as if it was written inside the sample class.
3. This block can be used to define Rails macros like validations, associations, and scopes.
4. Any method you create here becomes instance methods of the including class.
2. class_methods

1. Any methods that you add here become class methods on the including class.
Example:

typically concerns are located in app/controllers/concerns or app/models/concerns


module ExampleConcern
  extend ActiveSupport::Concern

  included do
    # any code that you want inside the class
    # that includes this concern
  end

  class_methods do
    # methods that you want to create as
    # class methods on the including class
  end
end


Including this concern in a controller:



class SomeController < ApplicationController
 include ExampleConcern
end


#RubyOnRails #concerns #CU6U0R822
author avatar

ayushsrivastava

Tue Oct 22 2024

We can generate a UUID in Rails using SecureRandom.uuid without needing any gem
#CU6U0R822
author avatar

giritharan

Mon Oct 21 2024

Managing Global Attributes with ActiveSupport::CurrentAttributes in Rails

In Rails, ActiveSupport::CurrentAttributes simplifies the process of storing global, thread-safe data like Current.user or Current.account during requests or jobs. It should be limited to top-level globals, such as user and request details, which are needed across all actions.

In controllers, Rails automatically resets Current between requests, so we don’t need to manually clear it. However, In Active Jobs, we need to manually reset Current after each job to prevent data from leaking between job executions. We achieve this using the after_perform callback.

Code Example:
*app/models/current.rb*:



class Current < ActiveSupport::CurrentAttributes
  attribute :user, :account, :request_id
end


app/jobs/my_job.rb:



class MyJob < ApplicationJob
  after_perform :clear_current_attributes

  def perform(params)
    set_current_attributes(params[:user_id])
  end

  private

  def set_current_attributes(user_id)
    Current.user = User.find_by(id: user_id)
    Current.request_id = SecureRandom.uuid
  end

  def clear_current_attributes
    Current.reset
  end
end


In summary: Rails handles resetting Current for controllers, but for jobs, we must manually reset it after each job to avoid data leakage.

#current #currentAttributes #CU6U0R822
author avatar

aman.suhag

Fri Oct 18 2024

In TypeScript, a tuple is a typed array with a fixed number of elements, where each element may have a different type. Unlike regular arrays, which can hold any number of elements of the same type, tuples define a specific sequence of element types and their corresponding positions.
Key Characteristics of Tuples:
1. Fixed Length: The number of elements in a tuple is fixed. You must specify how many elements the tuple can contain.
2. Different Types: Each element in a tuple can be of a different type. The type for each position is defined.
3. Access by Index: Elements are accessed by their index, just like regular arrays, but the types of the elements at each index are known and enforced by the type system.
let user: [string, number?] = ["Alice"]; // number is optional
#typescript #tuple
author avatar

ayasha.pandey

Fri Oct 18 2024

the fallbackData parameter in useSWR to provide default data for your fetch request. This is super useful when you want to display initial data while waiting for the network request to resolve. The fallback data will be used as the initial value for the data until the fetcher returns the actual data.



const {
  data,
  mutate,
  error,
} = useSWR(endpoint, fetcherFunction, {
  fallbackData: initialData,
});


#swr #hook

Showing 4 to 5 of 73 results