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

时间:2017-09-20 06:24:10

标签: ruby-on-rails vue.js strong-parameters

我试图将一些已检查的项目发布到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。知道为什么会这样吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

刚想通了。 Rails允许阵列字段的强大参数如下所示:

ParseTree entryPoint = parser.translationunit();

立即行动!