【问题标题】:Rails Hotwire + Admin NamespaceRails Hotwire + 管理员命名空间
【发布时间】:2022-01-04 03:31:34
【问题描述】:

我有一个运行 rails 6.1.3.2 的应用程序。我开始迁移以使用 hotwire 而不是 ujs。我的应用程序使用管理命名空间来允许用户进行编辑,通过它创建项目。下面的示例路线 -

resources :event_attachments
namespace :admin do
  resources :event_attachments
end

通过管理视图更新event_attachment 时,turbo_stream 不会在管理视图中处理部分内容,而是在查看EventAttachmentsController。我不确定它为什么这样做 - 任何建议都将不胜感激。

管理员:EventAttachmentsController -

  def update
    if @event_attachment.update(event_attachment_params)
      respond_to do |format|
        format.turbo_stream do
          render turbo_stream: [
            turbo_stream.update("flash", partial: "shared/flash", locals: { notice: "Event image updated" }),
            turbo_stream.replace(:event_attachments, partial: 'admin/pages/event_attachment', locals: { event_attachment: @event_attachment })
          ]
        end

        format.html do
          redirect_to edit_admin_event_attachment_path(@event_attachment), notice: 'Event image updated'
        end
      end
    else
      render :edit, status: :unprocessable_entity
    end
  end

这是我在admin/event_attachments 中的表单示例-

<%= form_for([:admin, event_attachment], :id =>  dom_id(event_attachment)) do |f| %>
  <%= f.text_field :title, :placeholder => "Event image name *" %>
<% end %>

Rails 服务器日志(作为测试,我在主 event_attachments 视图中创建了一个部分)-

Started PATCH "/event_attachments/25" for ::1 at 2022-01-03 22:18:53 -0500
Processing by EventAttachmentsController#update as TURBO_STREAM
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "event_attachment"=>{"title"=>"Test Name", "summary"=>"caption"}, "commit"=>"Save Changes", "id"=>"25"}
  EventAttachment Load (1.1ms)  SELECT `event_attachments`.* FROM `event_attachments` WHERE `event_attachments`.`id` = 25 LIMIT 1
  ↳ app/controllers/event_attachments_controller.rb:51:in `set_event_attachment'
  Rendered event_attachments/_event_attachment.html.erb (Duration: 0.1ms | Allocations: 22)
[ActionCable] Broadcasting to event_attachments: "<turbo-stream action=\"update\" target=\"event_attachment_25\"><template><li id=\"event_attachment_25\">\n  hello\n</li>\n</template></turbo-stream>"
Redirected to http://localhost:3000/event_attachments/25
Completed 302 Found in 4ms (ActiveRecord: 1.1ms | Allocations: 1640)

【问题讨论】:

    标签: ruby-on-rails hotwire-rails turbo-rails


    【解决方案1】:

    看起来这里的问题在于您的表单将请求发送到的 url。如果您查看日志,您会看到它说由 EventAttachmentsController#update 处理,这是因为您的表单中的 URL 是错误的。我的想法是你应该从使用 form_for 和 [] 改为使用 form_with

    <%= form_with(url: admin_event_attachments_path, :id =>  dom_id(event_attachment)) do |f| %>
      <%= f.text_field :title, :placeholder => "Event image name *" %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-03
      • 2015-04-05
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多