【问题标题】:Mass assign a collection of existing records rails批量分配现有记录轨道的集合
【发布时间】:2020-06-07 21:59:32
【问题描述】:

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

例如:

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"=&gt;"Standard location shoot", "items_attributes"=&gt;&lt;ActionController::Parameters {"1582459909419"=&gt;&lt;ActionController::Parameters {"id"=&gt;"1"} permitted: true&gt;} permitted: true&gt;}

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

【问题讨论】:

  • 你能分享你的list_params吗?
  • 正确是因为@list.items = items已经改变了items然后你仍然想更新if @list.update(list_params)中那些项目的属性
  • 谢谢我在上面的问题中添加了 list_params。 @list.items = items 是后来添加的,但如果我删除它,我会得到同样的错误。

标签: ruby-on-rails mass-assignment accepts-nested-attributes


【解决方案1】:

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

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

【讨论】:

  • 感谢您的快速回答。我的模型实际上属于“has_and_belongs_to_many”关联,所以item 没有list_id。相反,关联是通过一个连接表 list_items 完成的,其中每个记录都有一个 list_iditem_id
猜你喜欢
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 2020-09-04
  • 1970-01-01
  • 2012-06-14
相关资源
最近更新 更多