From Rails scaffold listing to Hotwire infinite scroll
source link: https://dev.to/andrzejkrzywda/from-rails-scaffold-listing-to-hotwire-infinite-scroll-3273
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
From Rails scaffold listing to Hotwire infinite scroll
Apr 22
・2 min read
Rails scaffold is a technique for quickly generating a typical CRUD UI.
It's a server-side rendered html which allows listing/editing/creating/deleting records.
One of the promises of the modern approach to building UI (like hotwire or stimulus reflex) is how easy it is to just tweak the backend logic, without using JavaScript at all.
Let's look at the example of infinite scroll - full tutorial how to do it is here and here.
I just want to focus on the "diff" how to make it work.
This is a typical Rails scaffold preparing all the posts to be displayed.
def index
@posts = Post.all
end
This is the equivalent Rails view (rendering html).
<% @posts.each do |post| %>
<div>
<h1><%= post.title %></h1>
<p><%= post.body %></p>
</div>
<% end %>
Now, in order to use Hotwire (actually Turbo Frame) we change the controller to this:
def index
@page = params[:page] ? params[:page].to_i : 1
offset = (@page - 1) * PER_PAGE
@posts = Post.offset(offset).limit(PER_PAGE)
@next_page = @page + 1 if @posts.size == PER_PAGE
end
In short, we pass 3 parameters to the view: page, posts, next_page.
And the view changes to this:
<%= turbo_frame_tag "posts_#{@page}" do %>
<% @posts.each do |post| %>
<div>
<h1><%= post.title %></h1>
<p><%= post.body %></p>
</div>
<% end %>
<% if @next_page %>
<%= turbo_frame_tag "posts_#{@next_page}", loading: :lazy, src: posts_path(page: @next_page) %>
<% end %>
<% end %>
We wrap the whole thing with a turbo_frame_tag
and we append more such frames for next pages. That's it.
As you can see the middle of the view stayed the same.
The UI now lists posts and keeps appending them when we scroll down.
I'm not claiming that it's amazing or something. But the practicality of getting our app more interactive, while not jumping to JavaScript is simple yet powerful.
I like it as it allows me to gradually extend my app with new features.
If you like audio to educate yourself then I recommend this podcast to learn more how it works:
https://www.codewithjason.com/rails-with-jason-podcast/episodes/092-vladimir-dementyev-5fK__ZQf/
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK