首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 7动态嵌套窗体与热弯/涡轮架?

Rails 7动态嵌套窗体与热弯/涡轮架?
EN

Stack Overflow用户
提问于 2022-04-01 22:21:49
回答 1查看 3.5K关注 0票数 7

我对铁轨很陌生。我从rails7开始,所以关于我的问题的信息仍然很少。

以下是我所拥有的:

app/models/cocktail.rb

代码语言:javascript
复制
class Cocktail < ApplicationRecord
  has_many :cocktail_ingredients, dependent: :destroy
  has_many :ingredients, through: :cocktail_ingredients
  accepts_nested_attributes_for :cocktail_ingredients
end

app/models/ingredient.rb

代码语言:javascript
复制
class Ingredient < ApplicationRecord
  has_many :cocktail_ingredients
  has_many :cocktails, :through => :cocktail_ingredients
end

app/models/cocktail_ingredient.rb

代码语言:javascript
复制
class CocktailIngredient < ApplicationRecord
  belongs_to :cocktail
  belongs_to :ingredient
end

app/controllers/cocktails_controller.rb

代码语言:javascript
复制
def new
  @cocktail = Cocktail.new
  @cocktail.cocktail_ingredients.build
  @cocktail.ingredients.build
end


def create
  @cocktail = Cocktail.new(cocktail_params)

  respond_to do |format|
    if @cocktail.save
      format.html { redirect_to cocktail_url(@cocktail), notice: "Cocktail was successfully created." }
      format.json { render :show, status: :created, location: @cocktail }
    else
      format.html { render :new, status: :unprocessable_entity }
      format.json { render json: @cocktail.errors, status: :unprocessable_entity }
    end
  end
end


def cocktail_params
  params.require(:cocktail).permit(:name, :recipe, cocktail_ingredients_attributes: [:quantity, ingredient_id: []])
end

...

db/籽实db

代码语言:javascript
复制
Ingredient.create([ {name: "rum"}, {name: "gin"} ,{name: "coke"}])

模式相关表

代码语言:javascript
复制
create_table "cocktail_ingredients", force: :cascade do |t|
    t.float "quantity"
    t.bigint "ingredient_id", null: false
    t.bigint "cocktail_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cocktail_id"], name: "index_cocktail_ingredients_on_cocktail_id"
    t.index ["ingredient_id"], name: "index_cocktail_ingredients_on_ingredient_id"
  end

create_table "cocktails", force: :cascade do |t|
  t.string "name"
  t.text "recipe"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "ingredients", force: :cascade do |t|
  t.string "name"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

...

add_foreign_key "cocktail_ingredients", "cocktails"
add_foreign_key "cocktail_ingredients", "ingredients"

app/views/cocktails/_form.html.erb

代码语言:javascript
复制
<%= form_for @cocktail do |form| %>
  <% if cocktail.errors.any? %>
    <% cocktail.errors.each do |error| %>
      <li><%= error.full_message %></li>
    <% end %>
  <% end %>

  <div>
    <%= form.label :name, style: "display: block" %>
    <%= form.text_field :name, value: "aa"%>
  </div>

  <div>
    <%= form.label :recipe, style: "display: block" %>
    <%= form.text_area :recipe, value: "nn" %>
  </div>

  <%= form.simple_fields_for :cocktail_ingredients do |ci| %>
    <%= ci.collection_check_boxes(:ingredient_id, Ingredient.all, :id, :name) %>
    <%= ci.text_field :quantity, value: "1"%>
  <% end %>

  <div>
    <%= form.submit %>
  </div>
<% end %>

当前错误:

鸡尾酒配料必须存在

我想要达到的目标是:

我想要一个部分,在那里我可以选择其中一种成分,并输入它的数量。应该添加/删除按钮来添加/删除成分。

我要用什么?涡轮机架?霍特维尔?我该怎么做?

我仍然对rails中的每一件事都非常困惑,所以我真的很想得到深入的答案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-02 07:54:46

代码语言:javascript
复制
1. Controller & Form - set it up as if you have no javascript,
2. Turbo Frame       - then wrap it in a frame.
3. TLDR              - if you don't need a long explanation.
4. Turbo Stream      - you can skip Turbo Frame and do this instead.
5. Bonus             - make a custom form field
6. Frame + Stream    - i didn't know you can do that

控制器与形式

首先,我们需要一个表单,可以提交,然后重新渲染,而不创建一个新的鸡尾酒。

使用accepts_nested_attributes_for确实会改变表单的行为,这并不明显,当您不理解它时,它会使您发疯。

首先,让我们修复表单。我将使用默认的rails表单生成器,但simple_form的设置也是相同的:

代码语言:javascript
复制
<!-- form_for or form_tag: https://guides.rubyonrails.org/form_helpers.html#using-form-tag-and-form-for
     form_with does it all -->
<%= form_with model: cocktail do |f| %>
  <%= (errors = safe_join(cocktail.errors.map(&:full_message).map(&tag.method(:li))).presence) ? tag.div(tag.ul(errors), class: "prose text-red-500") : "" %>

  <%= f.text_field :name, placeholder: "Name" %>
  <%= f.text_area :recipe, placeholder: "Recipe" %>

  <%= f.fields_for :cocktail_ingredients do |ff| %>
    <div class="flex gap-2">
      <div class="text-sm text-right"> <%= ff.object.id || "New ingredient" %> </div>
      <%= ff.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
      <%= ff.text_field :quantity, placeholder: "Qty" %>
      <%= ff.check_box :_destroy, title: "Check to delete ingredient" %>
    </div>
  <% end %>

  <!-- NOTE: Form has to be submitted, but with a different button,
             that way we can add different functionality in the controller
             see `CocktailsController#create` -->
  <%= f.submit "Add ingredient", name: :add_ingredient %>

  <div class="flex justify-end p-4 border-t bg-gray-50"> <%= f.submit %> </div>
<% end %>

<style type="text/css" media="screen">
  input[type], textarea, select { display: block; padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; width: 100%; border: 1px solid rgba(0,0,0,0.15); border-radius: .375rem; box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 3px 0px }
  input[type="checkbox"] { width: auto; padding: 0.75rem; }
  input[type="submit"] { width: auto; cursor: pointer; color: white; background-color: rgb(37, 99, 235); font-weight: 500; }
</style>

https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for

我们需要每一个cocktail_ingredient的单一成分,如belongs_to :ingredient所示。单一select是一个明显的选择;collection_radio_buttons也适用。

如果数据库中保存了特定的记录,fields_for助手将输出一个id为cocktail_ingredient的隐藏字段。这就是rails知道如何更新现有记录(使用id)并创建新记录(没有id)。

因为我们使用的是accepts_nested_attributes_for,所以fields_for将"_attributes“附加到输入名称中。换句话说,如果您的模型中有这样的内容:

代码语言:javascript
复制
accepts_nested_attributes_for :cocktail_ingredients

这意味着

代码语言:javascript
复制
f.fields_for :cocktail_ingredients

将以cocktail[cocktail_ingredients_attributes]作为输入名称的前缀。

(警告:源代码传入)原因是accepts_nested_attributes_for在Cocktail模型中定义了一个新的方法cocktail_ingredients_attributes=(params),它为您做了很多工作。这是嵌套参数为已处理的地方,CocktailIngredient对象被创建并分配给相应的cocktail_ingredients关联,如果_destroy参数为现在时,则还标记为销毁,而且由于autosave为设置 to true,因此可以获得自动验证。这只是一个FYI,如果您想要定义您自己的cocktail_ingredients_attributes=方法,并且您可以,f.fields_for将获取它的自动

在CocktailsController中,新的和创建的操作需要一个小的更新:

代码语言:javascript
复制
# GET /cocktails/new
def new
  @cocktail = Cocktail.new
  # NOTE: Because we're using `accepts_nested_attributes_for`, nested fields
  #       are tied to the nested model now, a new object has to be added to
  #       `cocktail_ingredients` association, otherwise `fields_for` will not
  #       render anything; (zero nested objects = zero nested fields).
  @cocktail.cocktail_ingredients.build
end

# POST /cocktails
def create
  @cocktail = Cocktail.new(cocktail_params)
  respond_to do |format|
    # NOTE: Catch when form is submitted by "add_ingredient" button;
    #       `params` will have { add_ingredient: "Add ingredient" }.
    if params[:add_ingredient]
      # NOTE: Build another cocktail_ingredient to be rendered by
      #       `fields_for` helper.
      @cocktail.cocktail_ingredients.build

      # NOTE: Rails 7 submits as TURBO_STREAM format. It expects a form to
      #       redirect when valid, so we have to use some kind of invalid
      #       status. (this is temporary, for educational purposes only).
      #       https://stackoverflow.com/a/71762032/207090

      # NOTE: Render the form again. TADA! You're done.
      format.html { render :new, status: :unprocessable_entity }
    else
      if @cocktail.save
        format.html { redirect_to cocktail_url(@cocktail), notice: "Cocktail was successfully created." }
      else
        format.html { render :new, status: :unprocessable_entity }
      end
    end
  end
end

在鸡尾酒模型中,允许在保存时使用_destroy表单字段删除记录:

代码语言:javascript
复制
accepts_nested_attributes_for :cocktail_ingredients, allow_destroy: true

就是这样,表单可以提交来制造鸡尾酒,也可以提交来添加另一种成分。

涡轮架

现在,当添加新的成分时,整个页面将被涡轮增压重新渲染。为了使表单更具动态性,我们可以添加turbo-frame标记来只更新表单的成分部分:

代码语言:javascript
复制
<!-- doesn't matter how you get the "id" attribute
     it just has to be unique and repeatable across page reloads -->
<turbo-frame id="<%= f.field_id(:ingredients) %>" class="contents">

  <%= f.fields_for :cocktail_ingredients do |ff| %>
    <div class="flex gap-2">
      <div class="text-sm text-right"> <%= ff.object&.id || "New ingredient" %> </div>
      <%= ff.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
      <%= ff.text_field :quantity, placeholder: "Qty" %>
      <%= ff.check_box :_destroy, title: "Check to delete ingredient" %>
    </div>
  <% end %>

</turbo-frame>

更改“添加成分”按钮,让turbo知道我们只想要提交页面的框架部分。一个普通的链接,不需要这个,我们只需要将这个链接放在框架标签中,但是一个输入按钮需要额外的注意。

代码语言:javascript
复制
<!-- same `id` as <turbo-frame>; repeatable, remember. -->
<%= f.submit "Add ingredient", 
  data: { turbo_frame: f.field_id(:ingredients)},
  name: "add_ingredient" %>

Turbo框架id必须匹配按钮的数据-turbo- frame属性:

代码语言:javascript
复制
<turbo-frame id="has_to_match">
<input data-turbo-frame="has_to_match" ...>

现在,当单击“添加成分”按钮时,它仍然会在服务器上呈现整个页面,但是没有重新呈现整个页面(框架#1),而是只更新turbo-frame中的内容(框架#2)。这意味着,页面滚动保持不变,表单状态之外的涡轮-框架标签是不变的.对于所有的意图和目的,这现在是一个动态的形式。

可能的改进是停止干扰创建操作,并通过不同的控制器操作添加成分,比如add_ingredient

代码语言:javascript
复制
# config/routes.rb
resources :cocktails do
  post :add_ingredient, on: :collection
end
代码语言:javascript
复制
<%= f.submit "Add ingredient",
  formmethod: "post",
  formaction: add_ingredient_cocktails_path(id: f.object),
  data: { turbo_frame: f.field_id(:ingredients)} %>

将add_ingredient操作添加到CocktailsController

代码语言:javascript
复制
def add_ingredient
  @cocktail = Cocktail.new(cocktail_params.merge({id: params[:id]}))
  @cocktail.cocktail_ingredients.build # add another ingredient

  # NOTE: Even though we are submitting a form, there is no
  #       need for "status: :unprocessable_entity". 
  #       Turbo is not expecting a full page response that has
  #       to be compatible with the browser behavior
  #         (that's why all the status shenanigans; 422, 303)
  #       it is expecting to find the <turbo-frame> with `id`
  #       matching `data-turbo-frame` from the button we clicked.
  render :new
end

现在可以将create操作恢复为默认操作。

您还可以重用new操作而不是添加add_ingredient

代码语言:javascript
复制
resources :cocktails do
  post :new, on: :new # add POST /cocktails/new
end

设置完全控制器:

https://stackoverflow.com/a/72890584/207090

然后将表单调整为post到new,而不是add_ingredient

TLDR -把它们放在一起

我认为这是我所能做到的最简单的事情。以下是简短的版本(添加动态字段的大约10行额外代码,没有javascript)

代码语言:javascript
复制
# config/routes.rb
resources :cocktails do
  post :add_ingredient, on: :collection
end

# app/controllers/cocktails_controller.rb 
# the other actions are the usual default scaffold
def add_ingredient
  @cocktail = Cocktail.new(cocktail_params.merge({id: params[:id]}))
  @cocktail.cocktail_ingredients.build
  render :new
end

# app/views/cocktails/new.html.erb
<%= form_with model: cocktail do |f| %>
  <%= (errors = safe_join(cocktail.errors.map(&:full_message).map(&tag.method(:li))).presence) ? tag.div(tag.ul(errors), class: "prose text-red-500") : "" %>
  <%= f.text_field :name, placeholder: "Name" %>
  <%= f.text_area :recipe, placeholder: "Recipe" %>

  <turbo-frame id="<%= f.field_id(:ingredients) %>" class="contents">
    <%= f.fields_for :cocktail_ingredients do |ff| %>
      <div class="flex gap-2">
        <div class="text-sm text-right"> <%= ff.object&.id || "New ingredient" %> </div>
        <%= ff.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
        <%= ff.text_field :quantity, placeholder: "Qty" %>
        <%= ff.check_box :_destroy, title: "Check to delete ingredient" %>
      </div>
    <% end %>
  </turbo-frame>

  <%= f.button "Add ingredient", formmethod: "post", formaction: add_ingredient_cocktails_path(id: f.object), data: { turbo_frame: f.field_id(:ingredients)} %>
  <div class="flex justify-end p-4 border-t bg-gray-50"> <%= f.submit %> </div>
<% end %>

# app/models/*
class Cocktail < ApplicationRecord
  has_many :cocktail_ingredients, dependent: :destroy
  has_many :ingredients, through: :cocktail_ingredients
  accepts_nested_attributes_for :cocktail_ingredients, allow_destroy: true
end
class Ingredient < ApplicationRecord
  has_many :cocktail_ingredients
  has_many :cocktails, through: :cocktail_ingredients
end
class CocktailIngredient < ApplicationRecord
  belongs_to :cocktail
  belongs_to :ingredient
end

涡轮流

Turbo流是尽可能动态的,我们可以在不接触任何javascript的情况下使用这个表单。我们必须改变形式,让我们呈现一种单一的鸡尾酒成分:

代码语言:javascript
复制
# NOTE: remove `f.submit "Add ingredient"` button
#       and <turbo-frame> with nested fields

# NOTE: this `id` will be the target of the turbo stream
<%= tag.div id: :cocktail_ingredients do %>
  <%= f.fields_for :cocktail_ingredients do |ff| %>
    # put nested fields into a partial
    <%= render "ingredient_fields", f: ff %>
  <% end %>
<% end %>

# NOTE: `f.submit` is no longer needed, because there is no need to
#       submit the form anymore just to add an ingredient.
<%= link_to "Add ingredient",
    add_ingredient_cocktails_path,
    class: "text-blue-500 hover:underline",
    data: { turbo_method: :post } %>
#                          ^
# NOTE: still has to be a POST request
代码语言:javascript
复制
<!-- app/views/cocktails/_ingredient_fields.html.erb -->
<div class="flex gap-2">
  <div class="text-sm text-right"> <%= f.object&.id || "New" %> </div>
  <%= f.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
  <%= f.text_field :quantity, placeholder: "Qty" %>
  <%= f.check_box :_destroy, title: "Check to delete ingredient" %>
</div>

更新add_ingredient操作以呈现turbo_stream响应:

代码语言:javascript
复制
# it should be in your routes, see previous section above.
def add_ingredient
  # NOTE: get a form builder but skip the <form> tag, `form_with` would work 
  #       here too. however, we'd have to use `fields` if we were in a template. 
  helpers.fields model: Cocktail.new do |f|
    # NOTE: instead of letting `fields_for` helper loop through `cocktail_ingredients`
    #        we can pass a new object explicitly.
    #                                   v
    f.fields_for :cocktail_ingredients, CocktailIngredient.new, child_index: Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) do |ff|
      #                                                         ^            ^ Time.now.to_f also works
      # NOTE: one caveat is that we need a unique key when we render this
      #       partial otherwise it would always be 0, which would override
      #       previous inputs. just look at the generated input `name` attribute:
      #          cocktail[cocktail_ingredients_attributes][0][ingredient_id]
      #                                                    ^
      #       we need a different number for each set of fields

      render turbo_stream: turbo_stream.append(
        "cocktail_ingredients",
        partial: "ingredient_fields",
        locals: { f: ff }
      )
    end
  end
end
# NOTE: `fields_for` does output an `id` field for persisted records
#       which would be outside of the rendered html and turbo_stream.
#       not an issue here since we only render new records and there is no `id`.

奖励-自定义表单生成器

让一个自定义字段助手将任务简化为一行:

代码语言:javascript
复制
# config/routes.rb
# NOTE: I'm not using `:id` for anything, but just in case you need it.
post "/fields/:model(/:id)/build/:association(/:partial)", to: "fields#build", as: :build_fields

# app/controllers/fields_controller.rb
class FieldsController < ApplicationController
  # POST /fields/:model(/:id)/build/:association(/:partial)
  def build
    resource_class      = params[:model].classify.constantize                                     # => Cocktail
    association_class   = resource_class.reflect_on_association(params[:association]).klass       # => CocktailIngredient
    fields_partial_path = params[:partial] || "#{association_class.model_name.collection}/fields" # => "cocktail_ingredients/fields"
    render locals: { resource_class:, association_class:, fields_partial_path: }
  end
end

# app/views/fields/build.turbo_stream.erb
<%=
  fields model: resource_class.new do |f|
    turbo_stream.append f.field_id(params[:association]) do
      f.fields_for params[:association], association_class.new, child_index: Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) do |ff|
        render fields_partial_path, f: ff
      end
    end
  end
%>

# app/models/dynamic_form_builder.rb
class DynamicFormBuilder < ActionView::Helpers::FormBuilder
  def dynamic_fields_for association, name = nil, partial: nil, path: nil
    association_class   = object.class.reflect_on_association(association).klass
    partial           ||= "#{association_class.model_name.collection}/fields"
    name              ||= "Add #{association_class.model_name.human.downcase}"
    path              ||= @template.build_fields_path(object.model_name.name, association:, partial:)
    @template.tag.div id: field_id(association) do
      fields_for association do |ff|
        @template.render(partial, f: ff)
      end
    end.concat(
      @template.link_to(name, path, class: "text-blue-500 hover:underline", data: { turbo_method: :post })
    )
  end
end

这个新的助手需要"#{association_name}/_fields"部分:

代码语言:javascript
复制
# app/views/cocktail_ingredients/_fields.html.erb
<%= f.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
<%= f.text_field :quantity, placeholder: "Qty" %>
<%= f.check_box :_destroy, title: "Check to delete ingredient" %>

覆盖默认表单生成器,现在应该有dynamic_fields_for输入:

代码语言:javascript
复制
# app/views/cocktails/_form.html.erb
<%= form_with model: cocktail, builder: DynamicFormBuilder do |f| %>
  <%= f.dynamic_fields_for :cocktail_ingredients %>
  <%# f.dynamic_fields_for :other_things, "Add a thing", partial: "override/partial/path" %>

  # or without dynamic form builder, just using the new controller
  <%= tag.div id: f.field_id(:cocktail_ingredients) %>
  <%= link_to "Add ingredient", build_fields_path(:cocktail, :cocktail_ingredients), class: "text-blue-500 hover:underline", data: { turbo_method: :post } %>
<% end %>

帧+流

您可以在当前页面上呈现turbo_stream标记,它将工作。仅仅为了把它移到同一页上的其他地方,渲染一些东西是很没用的。但是,如果我们把它放在一个turbo_frame中,我们可以在turbo_frame中获取更新的同时,将其移出框架之外以进行安全保存。

代码语言:javascript
复制
# app/controllers/cocktails_controller.rb
# GET /cocktails/new
def new
  @cocktail = Cocktail.new
  @cocktail.cocktail_ingredients.build
  # turbo_frame_request?           # => true
  # request.headers["Turbo-Frame"] # => "add_ingredient"
  # skip `new.html.erb` rendering if you want
  render ("_form" if turbo_frame_request?), locals: { cocktail: @cocktail }
end

# app/views/cocktails/_form.html.erb
<%= tag.div id: :ingredients %>

<%= turbo_frame_tag :add_ingredient do %>
  # NOTE: render all ingredients and move them out of the frame.
  <%= turbo_stream.append :ingredients do %>
    # NOTE: just need to take extra care of that `:child_index` and pass it as a proc, so it would be different for each object
    <%= f.fields_for :cocktail_ingredients, child_index: -> { Process.clock_gettime(Process::CLOCK_REALTIME, :microsecond) } do |ff| %>
      <%= ff.select :ingredient_id, Ingredient.all.map { |i| [i.name, i.id] }, include_blank: "Select ingredient" %>
      <%= ff.text_field :quantity, placeholder: "Qty" %>
      <%= ff.check_box :_destroy, title: "Check to delete ingredient" %>
    <% end %>
  <% end %>
  # NOTE: this link is inside `turbo_frame`, so if we navigate to `new` action
  #       we get a single set of new ingredient fields and `turbo_stream`
  #       moves them out again.
  <%= link_to "Add ingredient", new_cocktail_path, class: "text-blue-500 hover:underline" %>
<% end %>

没有额外的动作,控制器,路线,部分或响应。只有一个带有Html响应的GET请求,并且只追加了一组字段。我在任何地方都没有看到这个解释,希望这是预期的行为。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71713303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档