I send an email each week, trying 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 post by topic.
Maybe 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