【问题标题】:Editing Triple Nested Fields is Creating Duplicates Rails 5.1编辑三重嵌套字段正在创建重复 Rails 5.1
【发布时间】:2018-02-12 13:07:07
【问题描述】:

我有一个三重嵌套资源,我能够完美地创建新值。但是,在尝试编辑记录时,我得到了嵌套值的重复字段,然后创建了多个条目。

我将嵌套字段乘以 3。

  def new
    @roast = Roast.new
    3.times {@roast.countries.build.regions.build}
  end

编辑方法:

  def edit
    @roast = Roast.friendly.find(params[:id])
    3.times {@roast.countries.build.regions.build}
  end

我应该在这里删除“构建”元素吗?但是,如果需要,我确实希望用户能够添加新值。

create 对此并没有什么特别之处:

  def create
    @roast = Roast.new(roast_params)

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

我显然希望 3 个嵌套字段显示在编辑页面上,但我做错了什么让它不断重复。

【问题讨论】:

    标签: ruby-on-rails nested nested-forms


    【解决方案1】:

    您无需在编辑中添加国家或地区。只要找到烤肉。

    #This is wrong
    3.times {@roast.countries.build.regions.build}
    

    编辑 Roast 时,您可以通过 @roast.countries 访问其国家/地区 如果您愿意,您可以定义一个实例变量以在表单中使用(虽然不需要)@countries = @roast.countries

    【讨论】:

    • 再次感谢@Pablo。
    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多