How to submit an array field using a Rails form 提交包含数组字段的表单


下面仅仅显示部分重点代码

view:  _form.html.slim

= form_for item=@topic do |f|
  .mb-3
    = f.label :name
    = f.text_field :name, class: 'form-control'
  .mb-3 id="tagArray"
    = f.label :tags
    button id="addTagBtn" Add

    - if item.persisted?
      - item.tags.each do |x|
        = text_field_tag("topic[tags][]", x, { class: 'form-control'})
    = text_field_tag("topic[tags][]", nil, { class: 'form-control', placeholder: 'new tag'})


这里可以加一段js代码,加个按钮,点击后生成一个空的  input 元素
可以在 application.js下面加上这么一段,也可以单独做个js文件,import到application.js里面

# document.addEventListener("turbolinks:load", function() { 
# rails 7 使用hotwire后,需要监听的 turbo:load 事件了。
document.addEventListener("turbo:load", function() { 
  console.log("Turbo!")
  document.querySelectorAll('#addTagBtn').forEach(function(addTagBtn) {
    addTagBtn.addEventListener('click', function(event) {
      var x = document.createElement("INPUT");
      x.setAttribute("type", "text");  
      x.setAttribute("name", "topic[tags][]");
      x.setAttribute("class", "form-control");
      x.setAttribute("placeholder", "new tag");
      document.getElementById('tagArray').appendChild(x)
    })
  })
end



这里面的 tags 属于数组,不能使用 f.text_field 。 

form_for item=@topic do |f|
end
这里的 f 表示 FormBuilder, f.text_field(...) 没法生成   name="topic[tags][]" 这种名字的input,所以需要使用text_field_tag来生成类似下面的html代码。

= text_field_tag("topic[tags][]", ‘en’, { class: 'form-control', placeholder: 'new tag'})
= text_field_tag("topic[tags][]", nil, { class: 'form-control', placeholder: 'new tag'})
                   ⇓
<input type="text" name="topic[tags][]" value="en" class="form-control">
<input type="text" name="topic[tags][]" class="form-control" placeholder="new tag">


The variable f yielded to the block is a FormBuilder object
form_for(record, options = {}, &block)
text_field(object_name, method, options = {})   f

controller里面的只需要设置好tags:[]即可:

private
  def topic_params
    params.require(:topic).permit(:name, tags:[]);
  end


从turbolinks升级到hotwire和turbo  视频 

从turbolinks升级到hotwire升级文字版
阅读量: 357
发布于:
修改于: