将 Vue 表单元素发布到 Rails 5.1 控制器中

POSTing Vue form elements into a Rails 5.1 controller

我正在尝试 post 将一些选中的项目放入 Rails 控制器中,但似乎无法使其正常工作。

在我的表格中我有:

<%= form_for(listing, html: { id: listing.id, class: 'listing_form' }) do |f| %>
  ...

  <div v-for="(item, idx) in items">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input" v-model="checkedItems[idx]" :value="item.id">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description">{{ item.text }}</span>
    </label>
  </div>

  ...

  <div class="actions">
    <%= f.submit class: 'btn btn-success', 'v-on:click.prevent': 'submitListing' %>
  </div>
<% end %>

我的 Vue 代码如下所示:

if(document.getElementById('listing-multistep') != null) {
  Vue.http.headers.common['X-CSRF-Token'] = document.querySelector('input[name="authenticity_token"]').getAttribute('value');
  var listingForm = document.getElementsByClassName('listing_form')[0];
  var id = listingForm.dataset.id;

  const listingForm = new Vue({
    el: '#listing-multistep',
    data: {
      id: id,
      name: '',
      city: '',
      state: '',
      address: '',
      items: [
          {id: 0, text: "Item1"},
          {id: 1, text: "Item2"},
          {id: 2, text: "Item3"}
      ],
      checkedItems: []
    },
    methods: {
      submitListing: function() {
        var itemNames = []
        var checkedIndices = []

        // Probably a better way to do this...
        // Get the indices of all checkedItems that are true
        this.checkedItems.forEach((elt, idx) => {
          if(elt === true){ checkedIndices.push(idx) }
        });
        // Get the value of all the above indices    
        this.items.map((item) => {
          if(checkedIndices.includes(item.id)){
            itemNames.push(item.text);
          }
        });

        var listingObj = {
          id: this.id,
          name: this.name,
          city: this.city,
          state: this.state,
          address: this.address,
          items: itemNames  // <--- this is an array of items which isn't filtering through to Rails in the POST request
        }

        if(this.id == null) {
          console.log(listingObj)
          // POST the listingObj if it's a new listing
          this.$http.post('/listings', {listing: listingObj}).then(
            response => {
              window.location = `/listings/${response.body.id}`
          }, response => {
            console.log(response)
          })
        } else {
          // PUT the listingObj if it's an existing listing
          this.$http.put(`/listings/${this.id}`, {listing: listingObj}).then(
            response => {
              window.location = `/listings/${response.body.id}`
          }, response => {
            console.log(response)
          })
        }
      }
    }

虽然正在发送大部分数据并正在生成列表,但问题是 items 数组没有到达 Rails 控制器。

我的数据库是PostgreSQL,数据库中的条目定义如下schema.rb(所以数组字段应该是可能的):

t.text "items", default: [], array: true

我允许它通过我控制器中的强参数:

class ListingsController < ApplicationController

  ...

  private
  def listing_params
    params.require(:listing).permit(
      :name,
      :city,
      :state,
      :address,
      :items)
  end
end

但无法弄清楚为什么 listingOb 的 items 字段没有转移到 Rails。知道为什么会这样吗?

提前致谢

刚刚弄明白了。 Rails 中允许数组字段的强参数如下所示:

def listing_params
  params.require(:listing).permit(
    :name,
    :city,
    :state,
    :address,
    :items => []
  )
end

现在有效!