Проблема отправки формы Reactjs в модель Rails - PullRequest
0 голосов
/ 08 января 2019

Я смог отправить форму реагирования в режим rails, где поле существовало в той же таблице, где name="coffee_bean[country_id]" вставляет идентификатор country в таблицу coffee_beans. Это в форме для coffee_bean.

В качестве примера приведенный ниже код работает:

import React from 'react';
import axios from 'axios';
import Select from 'react-select';
import makeAnimated from 'react-select/lib/animated';

class Country extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      countries: []
    }
  }

  getCountries() {
    axios.get(`/countries.json`).then(res => {
      const countries = res.data;
      this.setState({countries});
    }).catch(error => console.log(error))
  }

  componentDidMount() {
    this.getCountries()
  }

  render() {
    let countryItems = this.state.countries.map(country => ({value: country.id, label: country.country_name}));
    return (<div className="">
      <label htmlFor="coffee_beans_country_id">Country</label>
      <Select isClearable="isClearable" components={makeAnimated()} id="country" name="coffee_bean[country_id]" options={countryItems}/>
    </div>)
  }
}

export default Country

Однако я сейчас пытаюсь повторить это, но для таблицы соединений, и здесь я застреваю. В настоящее время у меня есть код ниже, но это ничего не обновляет.

(просто для краткости показываю другой раздел рендера)

render() {
  let flavourItems = this.state.flavours.map(flavour => ({value: flavour.id, label: flavour.name}));
  return (
    <div className="">
      <label htmlFor="flavours">Flavours
        <small>(You can select more than one)</small>
      </label>
      <Select isMulti="isMulti" isClearable="isClearable" components={makeAnimated()} id="flavour" name="coffee_roast[flavour_id]" options={flavourItems}/>
    </div>
  )
}

Мои модели Rails

class CoffeeRoast < ApplicationRecord
    has_many :coffee_flavours
    has_many :flavour, through: :coffee_flavours

class Flavour < ApplicationRecord
  has_many :coffee_flavours
  has_many :coffee_roasts, through: :coffee_flavours

class CoffeeFlavour < ApplicationRecord #joins table
    belongs_to :flavour
    belongs_to :coffee_roast

форма рабочих рельсов Это было бы эквивалентно в рельсах.

<%= collection_check_boxes :coffee_roast, :flavour_ids, Flavour.all.order(name: :asc), :id, :name do |cb| %>
<% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text } %>

Рельсовая консоль

Processing by CoffeeRoastsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"jqLxq5Zw3/QIj169H5oAhQ3g69397xcTFEqpRr7x6q/Apfy8x9bcFhwv0NX41eWgYfNILA3OFnTadRqcpDDXrA==", "coffee_roast"=>{"roaster_id"=>"6", "name"=>"Los Rosales", "coffee_bean_ids"=>["", "5"], "flavour_ids"=>"3", "style"=>"Espresso", "strength"=>"Medium"}, "commit"=>"Update Coffee roast", "id"=>"los-rosales"}

flavour_id не похож на массив, и я ожидал бы, что он будет выглядеть как coffee_bean_ids. This then tells me flavour_ids не разрешен, но у меня это есть в качестве параметра в контроллере.

coffee_roasts_controller

class CoffeeRoastsController < ApplicationController
  before_action :set_coffee_roast, only: [:show, :edit, :update, :destroy]

  # GET /coffee_roasts
  # GET /coffee_roasts.json
  def index
    @coffee_roasts = CoffeeRoast.all
    @flavours = Flavour.all
    @meta_title = meta_title 'Coffee Roasts'
    @meta_description = 'A huge selection of coffee'

  end

  # GET /coffee_roasts/1
  # GET /coffee_roasts/1.json
  def show
    @coffee_roast = CoffeeRoast.friendly.find(params[:id])
    @flavour = Flavour.all
    @meta_title = meta_title @coffee_roast.name
    @coffeeroastcount = CoffeeRoast.where(roaster: @coffee_roast.roaster)
    @commentable = @coffee_roast
    @comments = @commentable.comments
    @comment = Comment.new
    @sameroaster = CoffeeRoast.where(roaster: @coffee_roast.roaster).where.not(name: @coffee_roast.name)

  end

  # GET /coffee_roasts/new
  def new
    @coffee_roast = CoffeeRoast.new
  end

  # GET /coffee_roasts/1/edit
  def edit
    @coffee_roast = CoffeeRoast.find(params[:id])
  end

  # POST /coffee_roasts
  # POST /coffee_roasts.json
  def create
    @coffee_roast = CoffeeRoast.new(coffee_roast_params)

    respond_to do |format|
      if @coffee_roast.save
        format.html { redirect_to @coffee_roast, notice: 'Coffee roast was successfully created.' }
        format.json { render :show, status: :created, location: @coffee_roast }
      else
        format.html { render :new }
        format.json { render json: @coffee_roast.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /coffee_roasts/1
  # PATCH/PUT /coffee_roasts/1.json
  def update
    @coffee_roasts = CoffeeRoast.all
    respond_to do |format|
      if @coffee_roast.update(coffee_roast_params)
        format.html { redirect_to @coffee_roast, notice: 'Coffee roast was successfully updated.' }
        format.json { render :show, status: :ok, location: @coffee_roast }
      else
        format.html { render :edit }
        format.json { render json: @coffee_roast.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /coffee_roasts/1
  # DELETE /coffee_roasts/1.json
  def destroy
    @coffee_roast.destroy
    respond_to do |format|
      format.html { redirect_to coffee_roasts_url, notice: 'Coffee roast was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_coffee_roast
      @coffee_roast = CoffeeRoast.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def coffee_roast_params
      params.require(:coffee_roast).permit(:name, :slug, :image, :flavours, :style, :strength, :roaster, :roaster_id, coffee_bean_ids:[], flavour_ids:[])
    end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...