发布于 2026-01-06 0 阅读
0

使用 hotwire-rails 在 Ruby on Rails 中实现实时局部更新

使用 hotwire-rails 在 Ruby on Rails 中实现实时局部更新

Basecamp 今天刚刚发布了 hotwire-rails。它是一套 JavaScript 和 Ruby 库的集合,可以用来打造非常丰富的用户体验

我最喜欢的一点是,在 Ruby on Rails 中创建实时局部视图非常容易。

现在我们只需要代码:

# app/models/post.rb
class Post < ApplicationRecord
  # We're going to publish to the stream :posts
  # It'll update the element with the ID of the dom_id for this object,
  # Or append our posts/_post partial, to the #posts <tbody>
  broadcasts_to ->(post) { :posts }
end
Enter fullscreen mode Exit fullscreen mode

然后,在这些观点中,有:

<!-- app/views/posts/index.html.erb -->
<%= turbo_stream_from :posts %>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Body</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody id="posts">
    <%= render @posts %>
  </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode
<!-- app/views/posts/_post.html.erb -->
<tr id="<%= dom_id post %>">
  <td><%= post.title %></td>
  <td><%= post.body %></td>
  <td><%= link_to 'Show', post %></td>
  <td><%= link_to 'Edit', edit_post_path(post) %></td>
  <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/mikerogers0/real-time-partial-updates-in-ruby-on-rails-using-hotwire-rails-1j1j