ruby-on-rails Rails 7 Turbo流/ Turbo帧,使用新项目渲染索引

w6lpcovy  于 2023-03-20  发布在  Ruby
关注(0)|答案(1)|浏览(206)

我有可怕的问题,试图让一个新的项目渲染回一个页面的索引使用涡轮流。
我想让它在创建动作后回到索引并将交易附加到页面,我需要这是一个涡轮流。到目前为止,当我创建它从来没有离开新的形式...我如何使创建动作使用涡轮流回到索引并附加新的交易。提前感谢
下面是我的代码

index.html.haml
%p{style: "color: green"}= notice
%h1 Deals
= turbo_frame_tag "deals" do
  - @deals.each do |deal|
    = render deal

= link_to "New deal", new_deal_path

_deal.html.haml
%div
  %p
    %strong Name:
    = deal.name

new.html.haml
%h1 New deal
= simple_form_for(@deal) do |f|
  %div
    = f.input :name
  %div
    = f.submit

deals_controller.rb
def create
    @deal = Deal.new(deal_params)
    respond_to do |format|
      if @deal.save
        format.turbo_stream
      end
    end
  end

create.turbo_stream.haml
= turbo_stream.prepend "deals", partial: "deals/deal", locals: { deal: @deal }
yrefmtwq

yrefmtwq1#

问题是你不想让用户重定向,相反,他们只是停留在索引页面,你只是 AJAX 发送表单提交,然后将新记录附加到现有文档中。
因此,让我们开始将表单重构为可重用的部分表单:

# deals/_form.html.haml
= simple_form_for(deal) do |f|
  %div
    = f.input :name
  %div
    = f.submit

然后让我们将表单放到索引视图中:

# deals/index.html.haml
%h1 Deals
= turbo_frame_tag "deal_form" do
  = render "form", deal: @deal

= turbo_frame_tag "deals" do
  = render @deals

我们还需要一个无效的形式提交涡轮流视图:

# deals/new.turbo_stream.haml
= turbo_stream.replace "deal_form" do
  = render partial: "deals/form", locals: { deal: @deal }

这里我们只是使用渐进式增强方法,表单和交易都呈现在初始页面视图中。使用turbo帧而不仅仅是div#deals在这种情况下实际上并没有做那么多,但如果你添加src属性来分解页面,它会在以后发挥作用。
然后,让我们设置控制器来将新交易流传输到列表中,或者在出现错误时“发送表单”。

class DealsController < ApplicationController

  # GET /deals or /deals.json
  def index
    @deals = Deal.all
  end

  # POST /deals or /deals.json
  def create
    @deal = Deal.new(deal_params)
    respond_to do |format|
      if @deal.save
        format.html { redirect_to action: :index, notice: "Deal was successfully created." }
        format.turbo_stream
      else
        format.html do 
          @deals = Deal.all
          render :index, status: :unprocessable_entity
        end
        format.turbo_stream { render :new, status: :unprocessable_entity }
      end
    end
  end

  private
    # Only allow a list of trusted parameters through.
    def deal_params
      params.require(:deal).permit(:name)
    end
end

Turbo还提供了直接为控制器渲染Turbo流的方法,如果您的操作足够简单,不需要视图:

def create
    @deal = Deal.new(deal_params)

    respond_to do |format|
      if @deal.save
        format.html { redirect_to action: :index, notice: "Deal was successfully created." }
        format.turbo_stream do
          render turbo_stream: turbo_stream.before(:deals, partial: "deals/deal", locals: { deal: @deal })
        end 
      else
        format.html { render :new, status: :unprocessable_entity }
        format.turbo_stream do
          render turbo_stream: turbo_stream.replace(:deal_form, partial: "deals/form", locals: { deal: @deal })
        end 
      end
    end
  end

相关问题