Mongoid + вложенные атрибуты кокона, вставляющие только последнюю дочернюю запись - PullRequest
0 голосов
/ 19 октября 2018

Я использую вложенные атрибуты для определения ассоциаций двух моделей (sites & site_units) в моем приложении rails 5.2 mongodb 4.0.Самоцвет mongoid версии 6 и также использует самоцвет кокона.Все работает нормально, что касается мнения.Проблема заключается в том, что при попытке добавить более 1 дочерних атрибутов при отправке в базу данных добавляется только последний дочерний атрибут.Ниже приведен мой пример кода:

app / models / site.rb

class Site
  include Mongoid::Document
  include Mongoid::Timestamps

  field :_id, type: Integer
  field :site_type_id, type: Integer
  field :code, type: String
  field :name, type: String
  field :description, type: String
  field :latitude, type: Float
  field :longitude, type: Float

  auto_increment :id, type: Integer

  has_many :site_units, inverse_of: :site

  accepts_nested_attributes_for :site_units, reject_if: proc { |attributes| attributes[:name].blank? }, allow_destroy: true
end

app / models / site_unit.rb

class SiteUnit
  include Mongoid::Document
  include Mongoid::Timestamps

  field :_id, type: Integer
  field :site_id, type: Integer
  field :code, type: String
  field :name, type: String
  field :description, type: String

  auto_increment :id, type: Integer

  belongs_to :site, optional: true
end

app / controllers / sites_controller.rb

class SitesController < ApplicationController
  before_action :authorize

  before_action :set_site, only: [:show, :edit, :update, :destroy]

  # GET /sites
  # GET /sites.json
  def index
    @sites = Site.all.page(params[:page])
  end

  # GET /sites/1
  # GET /sites/1.json
  def show
  end

  # GET /sites/new
  def new
    @site = Site.new
  end

  # GET /sites/1/edit
  def edit
  end

  # POST /sites
  # POST /sites.json
  def create
    @site = Site.new(site_params)

    @site.code.upcase!

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

  # PATCH/PUT /sites/1
  # PATCH/PUT /sites/1.json
  def update
    respond_to do |format|
      if @site.update(site_params)
        format.html { redirect_to @site, notice: 'Site was successfully updated.' }
        format.json { render :show, status: :ok, location: @site }
      else
        format.html { render :edit }
        format.json { render json: @site.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /sites/1
  # DELETE /sites/1.json
  def destroy
    @site.destroy
    respond_to do |format|
      format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_site
      @site = Site.find(params[:id].to_i)
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def site_params
      params.require(:site).permit(:site_type_id, :code, :name, :description, :latitude, :longitude,
                                    site_units_attributes: [:id, :site_id, :code, :name, :description, :_destroy])
    end
end

Я следовал этому же подходу с моим предыдущим проектом rails 5.2 + mariadb, и это сработало как шарм.Что я делаю не так здесь ... любая помощь будет высоко ценится.

...