【问题标题】:POSTing Vue form elements into a Rails 5.1 controller将 Vue 表单元素发布到 Rails 5.1 控制器中
【发布时间】:2017-09-20 06:24:09
【问题描述】:

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

提前致谢

【问题讨论】:

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


    【解决方案1】:

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

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

    现在可以使用了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多