I just released md_record, a Ruby gem that provides an ActiveRecord-like interface for markdown files with YAML frontmatter.
I have some posts about using lateral joins in rails to fetch the “top N” of each record. Some months ago Ben Sheldon helped me see a performance problem on the queries that I was using.
Here I try to explain the problem, the solution proposed by...
Read moreYesterday, I found myself struggling with “litesearch”, and in my frustration, I decided to create a simple “Searchable” module to perform a “LIKE” search but with a cleaner interface/API.
If you’re looking for a straightforward way to implement a...
Read moreI have already shared a way of implementing a “read-more” behavior truncating by the number of lines instead of the number of words.
But now I want to share how you can do it using the line-clamp css property.
I was reading about shoes.rb and, while scanning the book and walkthrough, I discovered a pattern that caught my attention for its power and simplicity.
The combination of “stacks” and “flows” allows you to build complex layouts, like the following...
Read moreN+1 queries are not always a problem, but I have seen that most of the n+1 queries that are really a problem are when we need to fetch data to compute something.
Here I will try to share some examples of posible expensive computations candidates to...
Read moreThere are many tools that can help you detect n+1 queries in different ways.
This is a little reference of some of those tools:
You don’t need to use all of them, but is good to know that they exists and how they can help you.
Imagine that you want to truncate a filename, but you want to keep showing the extension of the file. Like “A big file name that…awesome.pdf”. How would you do it?
Imagine that you are building a custom CMS. Within the form to edit an Article, you need to have two buttons: a normal “Save” button and a new “Save and publish” button. And maybe, additionally, you will need a third button to delete the article.
Imagine that you have a form to update a record (let’s say a product record) and inside the form, you are showing a list of images, and each image needs a button to remove it. You tried to use button_to but it doesn’t work because in html you can have...
Read moreIf you want to add images to a record but you don’t want to use a JavaScript plugin or write any custom JavaScript, you can use a regular file field, Active Storage, and vanilla Rails.
If you want to add many attachments to a record using just a file field, but you don’t want to remove the previous images from the record on every update, like in the following code:
When saving computed values in the database in your rails app, you must be aware that is possible to find unexpected errors in the result thanks to race conditions.
I have already shared an exercise to help you get more sensitivity about when an implementation...
Read moreWhen saving computed values in the database in your rails app, you must be aware that is possible to find unexpected errors in the result thanks to race conditions.
I have already shared an exercise to help you get more sensitivity about when an implementation...
Read moreWhen saving computed values in the database in your rails app, you must be aware that is possible to find unexpected errors in the result thanks to race conditions.
I have already shared an exercise to help you get more sensitivity about when an implementation...
Read moreWhen saving computed values in the database in your rails app, you must be aware that is possible to find unexpected errors in the result due to race conditions.
I have already shared an exercise to help you get more sensitivity about when an implementation...
Read moreI have already written about how you should be aware about race conditions when saving a computed value, because you could save a wrong value.
Here I want to share with you an exercise to help you (and me 😅) get more sensitivity about when an implementation...
Read moreWhen saving computed values in the database in your rails app, you must be aware that is possible to find unexpected errors in the result thanks to race conditions.
Here I want to help you visualize how race conditions can make you save incorrect...
Read moreIn Rails, sometimes you will need to save counts or custom computed values, where the default counter cache will not be enough.
Maybe you want to…
Imagine that you are creating a record (let’s say a tweet), and on creation, you want to add the tweet to the page and also update the tweets count in the page…
But you want to update the content, not just for the current user, but for all the users...
Read moreDo you want to build powerful admin interfaces with little code, but you are not sure if you want to jump into a full admin solution like Active Admin, Administrate or Avo?
Here I want to show you an alternative!
A step by step guide to build a dynamic...
Read moreHave you ever needed to get the most recent N posts for each user in rails, but didn’t know how to do it without using map?
Or maybe something similar like:
Have you ever needed to get the most recent N posts for each user in rails, but didn’t know how to do it?
Or maybe something similar like:
Have you ever wanted to just create an active record example to someone in your team without thinking in the database setup?
Or maybe send two different models designs with some examples to see the difference, but the setup what just to difficult...
Read moreDisplay the count of an association could look like a simple task, but in some cases it can give you real troubles.
It is very easy to end with n+1 queries. Counting with ruby sometimes can be ok, but sometimes could be impossible. Counting via sql...
Read moreHave you ever needed to get the most recent post for each user in rails, but didn’t know how to do it without using map?
Or maybe something similar, like:
Sometimes calculating the count of a collection on every page render, even in SQL, is not the best option.
Imagine that you need to render a post, with its count of likes and comments, but the post has thousands of likes and comments. That would be...
Read moreMaybe you have heard about the counter cache feature.
A counter cache makes finding the number of belonging objects more efficient by keeping a column with the count.
Rails makes it easy to implement it, but is not free. Sometimes it may be better...
Read moreMaybe you have heard about the counter cache feature.
It makes finding the number of belonging objects more efficient, by keeping a column with the count.
But… When should you use it? Do you need to have a counter cache for every association count...
Read moreAt least for me it is very common to use the within method in capybara, to match the dom_id output.
And is very common to do it with code like "#user_#{user.id}" or #project_#{project.id}.
Imagine that you need to put the number of likes for each post in a list, but avoiding n+1 queries.
posts.each do |post|
post.likes.count # n+1 queries
end
One way to avoid n+1 queries here, is to preload the association and the count the records...
Read moreWith Rails/ActiveRecord, you can count the records in an association using three methods .count, .length, .size.
As a rails newbie, when you first discover this, it can be confusing… Why do we need three methods? Is there any advantage to using one...
Read moreI want to share with you my “Active record playground template”.
It is a template that you could use as a guide or by cloning the repo and following the instructions in the README if you want to play with some Active Record models in isolation and without creating a full rails app.
It is very common the need to preload an association then filter that association and then use the filtered collection.
For example, imagine that you need to render a list of posts with just its
“popular” comments, where “popular” means “with a likes_count
I have seen that some people think that you have to forget about Rails and Hotwire, if you want to use React or another Javascript framework to build a Single Page Aplication, but this idea is not true.
You can use Rails and Hotwire as the base of...
Read moreWhen you start a new app or when things start to get complicated on the frontend side of your rails app, I think that it is normal to start thinking if you should split the app into a rails backend and a frontend with react, vue, or other javascript...
Read moreIf you are new with rails and hotwire, it could be useful to know that you can pass an object to the turbo_frame_tag and it will use a string representation of that object as an id.
I built a tool to comples css classes like this…
styles = Styler.new do
style :default, ["pa3", "white", "bg_blue"]
style :danger, [default - "bg_blue", "bg_red"]
end
styles.default.to_s # => "pa3 white bg_blue"
styles.danger.to_s # => "pa3 white...
Read more
This is a guide to help you build “inline CRUDs” with rails and hotwire, where you create and edit records in the same page.
Here I want to show you how you can build “remote modals” (modals where the content is requested to the server), submit forms embedded in them and handle errors, with rails, hotwire and bootstrap.
Have you been stuck trying to build a form to save more than one record?
Rails form helpers are really easy to work with when you are working with an
ActiveRecord::Base object…
But what do you do when you need to create a form to save multiple records...
Read moreA very common task as a Rails developer is to let the user filter a list with a combination of search fields and selects.
Here I want to show you one way of doing it using turbo and stimulus.js from hotwire, with an example app.
One of the things that I want from css is to have to possibility to compose already defined styles, to define new ones…
If you try to write “Semantic CSS”, you will find a hard time trying to avoid the repetition on things that look the same but are...
Read moreIf you work with capybara and you are constantly searching for capybara helpers, maybe to have this little cheatsheet at hand could work for you.
I already have share it on as a blog post, but now I want to share it with you as a pdf.
Maybe you are already familiar with includes or preload, but you know that a lot of the time you will need more than just preload(:comments).
I have already share with you a guide for preloading associations…
It starts with the basics, with just...
Read moreAlthough there are tools that can help you detect n+1 queries before they hit production, I think that is good to be able to identify n+1 queries directly by watching your logs…
Not all the tools will tell you exactly that you have n+1 queries, and...
Read moreMaybe you already know that “fixing” an n+1 queries problem can hurt the performance of your app…
But even if you already know it and also understand how it can happen, it could not be obvious how to know if this is will happen with your fix.
Some...
Read moreWhen you are working with SQL, to use information from other tables you would use a JOIN…
And if you are just starting to learn ActiveRecord comming from SQL, you could
think that by using the joins method you will be able to later use the data
from...
I want to share with you an example application to help you visualize why “fixing” an n+1 queries problem, can hurt the performance of your application if you preload assocations with too many records.
It simulates the index page of a blog application...
Read moreSometimes people say that “fixing” some n+1 queries could hurt performance…
Maybe this phrase can be confusing, because if you have not been exposed to a lot of n+1 queries problems, it could be hard to imagine how it can be possible.
And also is...
Read moreI want to tell you that I have added a new section to the guide for preloading associations in rails, to introduce you to something I call “Preload objects” that will help you build complex preloads for those cases when you can’t find a way to do what you need to do, with the standard rails mechanisms.
Sometimes just using preload or includes is not possible… or maybe it is, but you just can’t figure it out how to do it.
Maybe you want to preload some records matching two keys, or preload a grouped relation.
Maybe you know how to represent the association with a has_many
:through, but you need something faster, or to use less memory.
In that kind of situations, one thing that you can do is to write a custom object to represent that preload.
Here I will try to explain how and when you can do it with an example.
Maybe you are already familiar with includes or preload, but you know
that a lot of the time you will need more than just preload(:comments).
It is common to have complex nested associations, scopes that you need or want to reuse, places where preloading all the associated records could hurt the performance of your app.
How do you work with complex nested associations?… How do you simplify the preloading of those nested associations?… How do you “preload an scope”?… How do you preload just the latest n of each record?
An n+1 queries problem means that a query is executed for every result of a previous query.
For example, with this records…
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
If you...
Read moreA common cause of n+1 queries is fetching the “latest-N-of-each” record on a list of records.
Some examples of this problem are trying to get…
There are different practices, that I know, to test that an email was sent in Rails…
If you want to test that an email was sent on a system spec in rails…
What you can do is to check the ActionMailer::Base.deliveries to see if the email that you want is there.
As you may now there are two hard things in computer science and one of them is naming things.
And although naming things is an art, is not bad to have a little guide on how to do it.
That’s why I want to share with you a guide on how to name scopes...
Read moreI like heroku, it is very easy to use, but sometimes you just can’t use it…
Maybe it is too expensive for your project. Maybe you need something that it does not provide, like an integrated “S3-storage”. Maybe for some reason you are forced to run...
Read moreMaybe your are thinking that you should just use Heroku and move on with your life. Do something that provides value to the customer instead of host configurations.
But is not always that easy, because if you just compare the cost of GB of Ram or...
Read moreFor most of us, heroku is a really useful tool because it does so much for us, but in some cases it could look like it is really expensive…
… Is it really expensive? Does it worth the time it saves on tooling, maintenance, devops, etc? Would you be...
Read moreImagine that you need to query for the payments received the “week before” of a given date.
How would you expose this feature in your model?
In this article I want to share some ways of doing it, by telling the story of what we did in a similar case…
Imagine that you need to query for the records created in the “week before” of a given date.
How would you do it?
This was new for me, I was looking how to get the noCertificado from a CSD
(Certificado de Sello Digital) and I found it is the serial of the
certificate but in base 2.
Do you want to test a PDF download with capybara, but don’t know how to do it?
Here I will how you can doing it are using the default driver (not the javascript driver).
Do you need/want to test a CSV download with capybara, but don’t know how to do it?
Here I will show you a simple way of doing it if you are using the default driver.
A code sample of a “read-more” behavior using the rails truncate method and Stimulus.js.
Are you looking for a way of implementing a “read-more” behavior truncating by the number of lines instead of the number of words?
Are you working with capybara?… Are you constantly searching for capybara helpers?
Here is a small reference with some of the most used methods/helpers.
Imagine that you want to refactor this…
expect(row).to have_css("[data-role=description]", text: "Desc 1")
expect(row).to have_css("[data-role=amount]", text: "$250.00")
into this…
expect(row).to display_entry_with("Desc1", $250.00)
Do you need more practice to understand the difference between “includes”, “preload”, “eager_load” and “joins”?
Here you will find a set of exercises to help you understand how you can use this 4 methods.
You can find the code on bhserna/preloading_quiz
Read moreI am currently working on a kind of “presentation object” that I called IdealPayments::GlobalStats.
This object will be used in two places, to display a graph and to show the data in a page where we can see all the “ideal payments”.
In my imagination...
Read moreDo you know “in theory” the difference between “includes”, “preload”, “eager_load” and “joins”, but you still think that you need more examples to really understand how to use them?
Here you will find a set of examples to help you understand how you...
Read moreDo you know “in theory” the difference between “includes”, “preload”, “eager_load” and “joins”, but you still think that you need more examples to really understand how to use them?
Here you will find a set of examples to help you understand how you...
Read moreAre you using Active Storage to handle file uploading to the cloud (maybe AWS) and you want to know how to attach an uploaded file to an email?… But you are not familiar with the Active Storage and Action Mailer APIs?
I answered this question on reddit...
Read moreEven if you already know what is the difference between includes, preload and eager_load, maybe is not that clear when is better for you to use one vs the other.
Are you dealing with includes, preload, eager_load and joins, maybe fixing some n+1 queries, but you are not really sure what’s the difference between all of them?
Would you like to be able to say things like… “Here I will use preload instead of
A common cause of n+1 queries is fetching the “latest-N-of-each” record on a list of records.
Some examples of this problem are trying to get…
Do you struggle fixing N+1 queries because is hard for you to detect why ActiveRecord seems to ignore your “includes”?
Wouldn’t it be nice to just see some piece of code and know when the query will execute?
Well… this exercise will try to help you...
Read moreDo you have a method that works fine with a single record, but when you use it on a list causes N+1 queries?
Imagine that you have a model like this…
When you are trying to solve an n+1 problem, hopefully you will find different ways to solve it. But what is the one that you should use?
Talking specifically about the fixes that I share to you to solve the “latest comment” n+1 queries problem… I...
Read moreWhat fix should you pick for your “latest-comment” n+1 queries problem?
One example of this problem is trying to get the latest comment on a list of posts, but there are others, like the last review in a list of products, or the cheapest price, or...
Read moreDo you have to fetch the latest “x” of each record? Not sure how to avoid the n+1 queries?
Hopefully you will find different ways to solve it. But what is the one that you should use?
You can search the internet, but opinions can be overwhelming...
Read moreDo you have to fetch the latest “x” of each record?
One example of this problem is trying to get the latest comment on a list of posts, but there are others, like the last review in a list of products, or the cheapest price, or the latest payment...
Read moreWhat fix should you pick for your n+1 queries problem?
When you are trying to solve an n+1 problem, hopefully you will find different ways to solve it. But what is the one that you should use?
You can search the internet, but opinions can be overwhelming...
Read moreDo you have a method that works fine with a single record, but when you use it on a list causes N+1 queries?
One example of this problem is trying to get the latest comment on a list of posts, but there are others, like the last review in a list of...
Read moreHave you ever implemented a feature that does work, but has resulted in using multiple conditionals in your controller and views… Wondering if there is a better way to do what you just did?
Maybe your problem is that you have a hidden abstraction...
Read moreDo you have a method that works fine with a single record, but when you use it on a list causes N+1 queries?
Maybe, you are building a rails app and you want to fetch a list of posts with the latest comment (or something similar)…
You have a model...
Read moreHere I try to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or all posts.