0

我正在尝试将现有记录的集合分配给现有(或新)关联记录。

例如:

class List < ApplicationRecord
    has_and_belongs_to_many :items, join_table: :list_items
    accepts_nested_attributes_for :items
end
class Item < ApplicationRecord
    has_and_belongs_to_many :lists, join_table: :list_items
end

从我对列表的创建或编辑表单的视图来看,我正在发送 :name 以及 :items_attributes 以及我想要关联到我的列表的每条记录的 :id。

在我的列表控制器中,我这样做:

def update
    items = Item.where(id: list_params[:items_attributes][:id])
    @list.items = items

    respond_to do |format|
// the following line breaks, because @list currently has no "item" (the
// association built previously hasn't been saved yet) 
      if @list.update(list_params)
        format.html { redirect_to @list, notice: 'List was successfully updated.' }
        format.json { render :show, status: :ok, location: @list }
      else
        format.html { render :edit }
        format.json { render json: @list.errors, status: :unprocessable_entity }
      end
    end
  end

但是,我越来越

ActiveRecord::RecordNotFound in ListsController#update

Couldn't find Item with ID=1 for List with ID=1

我将如何以“Rails”方式保存此关联?

编辑

list_params会是这样的(使用 Cocoon gem):

{"name"=>"Standard location shoot", "items_attributes"=><ActionController::Parameters {"1582459909419"=><ActionController::Parameters {"id"=>"1"} permitted: true>} permitted: true>}

未过滤的参数是: {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"qkXKM9U/1+Y8T4RttvPg==", "list"=>{"name"=>"Standard location shoot", "items_attributes"=>{"1582459152520"=>{"id"=>"1", "_destroy"=>"false"}}}, "commit"=>"Update List", "controller"=>"lists", "action"=>"update", "id"=>"1"}

更一般地说,定义为list_params

# Never trust parameters from the scary internet, only allow the white list through.
    def list_params
      params.fetch(:list, {}).permit(:name, items_attributes: [:id])
    end
4

1 回答 1

0

@list.items = items平均列表有很多项目,项目表有 list_id 列。

你可以试试@list.update item_ids: list_params[:items_attributes][:id]

于 2020-02-24T09:59:53.270 回答