vaibhav.yadav
Thu May 23 2024
Use
#git #gitReset #github
git reset --mixed HEAD~1
command to undo your last commit without losing the changes made in your last commit.#git #gitReset #github
adithya.hebbar
Thu May 23 2024
In TypeScript interfaces,
#javascript #typescript
?:
denotes optional properties. Here's an example:
interface User {
name: string;
age?: number; // Optional
}
const user1: User = { name: "Joe Mama" }; // Age is optional
const user2: User = { name: "Tony", age: 30 };
console.log(user1); // Output: { name: "Joe Mama" }
console.log(user2); // Output: { name: "Tony", age: 30 }
#javascript #typescript
adithya.hebbar
Thu May 23 2024
Utility Types:
TypeScript's Utility Types simplify complex type manipulations. For instance,
#javascript #typescript
TypeScript's Utility Types simplify complex type manipulations. For instance,
Partial<T>
makes all properties of type T optional
interface User {
id: number;
name: string;
email: string;
}
function displayUser(user: Partial<User>) {
console.log(user);
}
displayuser({ name: "Joe Mama" }); // Partial<T> will make the properties optional hence this is valid
#javascript #typescript
ayushsrivastava
Thu May 23 2024
EAGER LOADING
Eager loading in Rails is a technique used to optimize database queries by loading associated records of the objects returned by the query, thereby reducing the number of database calls. This is particularly useful when you have associations defined in your models and you want to avoid the "N+1 query problem."
What is the N+1 Query Problem?
“N+1 Queries” are a very common cause of repeated queries in Rails applications. This happens when you make a request for a single row in one table, and then make an additional request per element in a
Here’s an example:
Consider two models:
Scenario Without Eager Loading
When you fetch authors and then access their books, Rails performs an additional query for each author to get their books.
This will result in one query to fetch the authors and multiple queries to fetch books for each author, leading to the N+1 query problem.
How Eager Loading Works
Eager loading addresses this problem by loading all the necessary data in as few queries as possible, usually through the use of
Using Eager Loading with
To avoid the N+1 query problem, you can use
With
Using Eager Loading with
This approach performs a single query with a
Using Eager Loading with
Summary
Eager loading is a powerful tool in Rails that helps to optimize database access by pre-loading associations. Using
#rails #db #optimizing_queries
Eager loading in Rails is a technique used to optimize database queries by loading associated records of the objects returned by the query, thereby reducing the number of database calls. This is particularly useful when you have associations defined in your models and you want to avoid the "N+1 query problem."
What is the N+1 Query Problem?
“N+1 Queries” are a very common cause of repeated queries in Rails applications. This happens when you make a request for a single row in one table, and then make an additional request per element in a
has_many
relationship, usually in a loop.Here’s an example:
Consider two models:
Author
and Book
, where an Author
has many Books
.
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
Scenario Without Eager Loading
When you fetch authors and then access their books, Rails performs an additional query for each author to get their books.
# Fetching all authors and their books
authors = Author.all
authors.each do |author|
puts author.books.pluck(:title)
end
This will result in one query to fetch the authors and multiple queries to fetch books for each author, leading to the N+1 query problem.
How Eager Loading Works
Eager loading addresses this problem by loading all the necessary data in as few queries as possible, usually through the use of
includes
, eager_load
, or preload
.Using Eager Loading with
includes
To avoid the N+1 query problem, you can use
includes
to preload the associated books when fetching authors.
# Fetching all authors and their books with eager loading
authors = Author.includes(:books)
authors.each do |author|
puts author.books.pluck(:title)
end
With
includes
, Rails performs a single query to fetch all authors and another single query to fetch all associated books.Using Eager Loading with
eager_load
eager_load
forces Rails to use a SQL JOIN
to load the associated records. This can be useful if you need to filter or sort based on the associated records.
# Fetching all authors and their books with eager loading using JOIN
authors = Author.eager_load(:books)
authors.each do |author|
puts author.books.pluck(:title)
end
This approach performs a single query with a
LEFT OUTER JOIN
.Using Eager Loading with
preload
preload
is similar to includes
, but it always uses separate queries for loading the associations.
# Fetching all authors and their books with eager loading using separate queries
authors = Author.preload(:books)
authors.each do |author|
puts author.books.pluck(:title)
end
preload
is useful when you know that separate queries will be more efficient, for example, when fetching a large number of records.Summary
Eager loading is a powerful tool in Rails that helps to optimize database access by pre-loading associations. Using
includes
, eager_load
, or preload
appropriately can significantly improve the performance of your application by reducing the number of database queries.#rails #db #optimizing_queries
ayushsrivastava
Tue May 21 2024
Scoped Associations with Joins
Let's consider the following models:
•
•
The association is that an
Defining Scoped Associations
First, let's define a scope on the
Next, let's use this scope in the
Now,
Using Scoped Associations with Joins
We can now use the scoped association in joins to fetch authors and their published books.
Example 1: Fetch Authors with Published Books
To fetch authors along with their published books:
This query joins the
As a result, each
• All attributes of the
• An additional attribute called
#rails #scoped_associations_with_joins
Let's consider the following models:
•
Author
with attributes id
, name
•
Book
with attributes id
, title
, published
, author_id
The association is that an
Author
has many Books
, and a Book
belongs to an Author
.Defining Scoped Associations
First, let's define a scope on the
Book
model to filter only published books:
class Book < ApplicationRecord
belongs_to :author
scope :published, -> { where(published: true) }
end
Next, let's use this scope in the
Author
model to create a scoped association:
class Author < ApplicationRecord
has_many :books
has_many :published_books, -> { published }, class_name: 'Book'
end
Now,
Author
has an association called published_books
, which only includes books that are published.Using Scoped Associations with Joins
We can now use the scoped association in joins to fetch authors and their published books.
Example 1: Fetch Authors with Published Books
To fetch authors along with their published books:
@authors_with_published_books = Author.joins(:published_books).select('authors.*, books.title as book_title')
This query joins the
authors
table with the books
table but only includes books that are published, thanks to the scoped association published_books
.As a result, each
Author
object in @authors_with_published_books
will have:• All attributes of the
Author
model.• An additional attribute called
book_title
representing the title of each associated book.#rails #scoped_associations_with_joins
ayushsrivastava
Tue May 21 2024
Scoped associations
Let's say we have two models:
But what if we don't ever want to include posts for user which are published? Often I see people doing this:
And this is fine, but you can somehow forget to add
#rails #database #model #associations
Let's say we have two models:
User
and Post
. And we want to get all posts for user. We can do this:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
user = User.first
user.posts
But what if we don't ever want to include posts for user which are published? Often I see people doing this:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
scope :published, -> { where(published: true) }
end
user = User.first
user.posts.published
And this is fine, but you can somehow forget to add
published
scope to your query. And then you will get all posts, even unpublished. And this is not what you want. Some people use default_scope
for this, but it is not good idea. So what we can do? We can use scope
in association:
class User < ActiveRecord::Base
has_many :posts, -> { published }
has_many :not_published_posts, -> { not_published }
end
class Post < ActiveRecord::Base
belongs_to :user
scope :published, -> { where(published: true) }
scope :not_published, -> { where(published: false) }
end
user = User.first
user.posts # only published posts here
#rails #database #model #associations
giritharan
Mon May 20 2024
There are two ways to call respond_to: Either we can pass it as a list of symbols or pass a block
Block Version:
Symbol version:
#respondto #actionview #rails
Block Version:
def index
@people = Person.all
respond_to do |format|
format.json { render json: @people}
format.xml { render xml: @people }
format.html { render :index}
end
end
Symbol version:
def index
@people = Person.all
respond_to :json, :xml, :html
end
#respondto #actionview #rails
soniya.rayabagi
Mon May 20 2024
kubectl rollout restart deployment <deployment-name>
command used to restart pods managed by a Kubernetes deployment without making any modifications to the deployment configuration.#devops #Kubernetes #rollingrestart
syedsibtain
Mon May 13 2024
Active Record is the Object-Relational Mapping (ORM) layer provided by Ruby on Rails. It facilitates the interaction between Ruby objects and a relational database. It helps us interact with our database using Ruby instead of writing SQL queries directly.
Key features of ActiveRecord include:
• Model Definition: ActiveRecord allows developers to define models that represent database tables. These models inherit from the ActiveRecord::Base class and include methods for defining associations, validations, and callbacks.
• CRUD Operations: ActiveRecord provides methods for performing CRUD (Create, Read, Update, Delete) operations on database records. These methods allow developers to manipulate records using Ruby syntax without writing explicit SQL queries.
• Associations: ActiveRecord simplifies the definition and management of associations between models. It supports various types of associations, including
• Validations: ActiveRecord includes a robust validation framework for ensuring data integrity. We can define validation rules such as presence, uniqueness, length, format, and custom validations to enforce data constraints at the model level.
#orm #rails
Key features of ActiveRecord include:
• Model Definition: ActiveRecord allows developers to define models that represent database tables. These models inherit from the ActiveRecord::Base class and include methods for defining associations, validations, and callbacks.
• CRUD Operations: ActiveRecord provides methods for performing CRUD (Create, Read, Update, Delete) operations on database records. These methods allow developers to manipulate records using Ruby syntax without writing explicit SQL queries.
• Associations: ActiveRecord simplifies the definition and management of associations between models. It supports various types of associations, including
belongs_to, has_many, has_one,
and has_and_belongs_to_many,
allowing us to express complex relationships between database tables.• Validations: ActiveRecord includes a robust validation framework for ensuring data integrity. We can define validation rules such as presence, uniqueness, length, format, and custom validations to enforce data constraints at the model level.
#orm #rails
giritharan
Mon May 13 2024
What is happening behind the scenes after we configured database credentials in database.yml
• Conduct the
• Exchange preferences and requirements with the database software to establish the session parameters.
• Perform
• PostgreSQL supports several authentication methods, such as passwords (plaintext or MD5),GSSAPI, SSPI, and more.
• The client (Rails, via ActiveRecord) can now send commands to the server. Commands are typically SQL statements. These statements are sent as simple text strings in the 'Query' message format.
How Number of connection affects the database server
• When the number of connections or pools to a server increases, CPU usage will rise. This increased demand for memory and CPU resources can affect other operations, such as transaction speeds. Managing many connections can also reduce the effectiveness of the database and decreasing overall system performance.
What will happen if we give more connections then we configured in PSQL?
• When that limit of a db is reached, additional connection requests are rejected.
How connections b/w rails and PSQL established and maintained?
•
• Establishing the connections is a fairly long operation.
•
• Once the response is returned it closes the connection. But the thing here is opening and closing connection is not overhead comparatively with client and DB connections.
#orm #activerecord #psql #rails
• Conduct the
three-way handshake
to establish a TCP connection to the server.• Exchange preferences and requirements with the database software to establish the session parameters.
• Perform
database authentication
checks to establish the client's identity.• PostgreSQL supports several authentication methods, such as passwords (plaintext or MD5),GSSAPI, SSPI, and more.
• The client (Rails, via ActiveRecord) can now send commands to the server. Commands are typically SQL statements. These statements are sent as simple text strings in the 'Query' message format.
How Number of connection affects the database server
• When the number of connections or pools to a server increases, CPU usage will rise. This increased demand for memory and CPU resources can affect other operations, such as transaction speeds. Managing many connections can also reduce the effectiveness of the database and decreasing overall system performance.
What will happen if we give more connections then we configured in PSQL?
• When that limit of a db is reached, additional connection requests are rejected.
How connections b/w rails and PSQL established and maintained?
•
Connection pooling
is a technique where database connections are reused for multiple requests instead of being closed after each query. This approach uses a connection pooler
, a software that manages the connections between the database and its client applications, optimizing the use of resources and improving performance.• Establishing the connections is a fairly long operation.
•
Connection pooler
is sitting b/w client and server. client connects to the connection pooler instead of directly to the database. Req is sent to pooler and the pooler interprets queries returns back the response from DB.• Once the response is returned it closes the connection. But the thing here is opening and closing connection is not overhead comparatively with client and DB connections.
#orm #activerecord #psql #rails
Showing 12 to 14 of 71 results