Ruby on rails 由于格式错误,控制器未在Rails中建立关联

Ruby on rails 由于格式错误,控制器未在Rails中建立关联,ruby-on-rails,ruby,controller,associations,Ruby On Rails,Ruby,Controller,Associations,我需要为修改模型if.save建立新的关联。此外,这些关联需要与相关的实体模型相同。但我得到了一个错误: 分配属性时,必须将哈希作为参数传递 ModificationController.rb def create @modification = Modification.new(change_params) respond_to do |format| if @modification.save @modification.entity.boxe

我需要为
修改
模型
if.save
建立新的关联。此外,这些关联需要与相关的
实体
模型相同。但我得到了一个错误:

分配属性时,必须将哈希作为参数传递

ModificationController.rb

def create
    @modification = Modification.new(change_params)

    respond_to do |format|
      if @modification.save

        @modification.entity.boxes.each do |d| 
          @modification.boxes.new(d)
        end

        flash[:success] = "Success"
        format.html { redirect_to @modification }
        format.json { render :show, status: :created, location: @modification }
      else
        format.html { render :new }
        format.json { render json: @modification.errors, status: :unprocessable_entity }
      end
    end
  end
更多信息:

每个
修改
都属于
实体

修改
实体
都有许多

当您声明一个有许多关联时,声明类会自动获得与该关联相关的16个方法

def创建
@修改=修改。新建(更改参数)
回应待办事项|格式|
if@modification.save
@修改.entity.box.each do|d|

@modify.boxes因此您希望使用现有的
box
创建一个新的box关联。我们可以抓取现有框的属性来创建新框。但是,现有的框已经有一个
id
,因此我们需要将其从属性中排除

按照上述逻辑,以下各项应起作用:

def create
  @modification = Modification.new(change_params)

  respond_to do |format|
    if @modification.save

      @modification.entity.boxes.each do |d| 
        @modification.boxes << d.dup
      end

      flash[:success] = "Success"
      format.html { redirect_to @modification }
      format.json { render :show, status: :created, location: @modification }
    else
      format.html { render :new }
      format.json { render json: @modification.errors, status: :unprocessable_entity }
    end
  end
end
def创建
@修改=修改。新建(更改参数)
回应待办事项|格式|
if@modification.save
@修改.entity.box.each do|d|

@modify.box是否为
box
关联?如果是这样,
d
是一个
,这样做
@modification.Box.new(d)
将产生您提到的错误消息。是。框是关联。
@modification.Box,或者可能是
@modification.Box.create!(d.attributes)
(至少在rails 3中)看起来是正确的,但它为已经制作好的框建立了新的关联。我需要做一个全新的盒子。我该怎么做?你能添加更多关于模型的关联信息吗?该模型现在有以下错误:唯一约束失败:box.idOk,hmmm。。。您是否包括
。除了(:id)
位之外?我是否应该将部分代码放入
私有
?因为现在我得到了这个错误:ActiveModel::ForbiddenAttribute错误。是的,我包括
。除了(:id)
好的,您需要使用Rails 4代码。我刚刚更新了它。。。我遗漏了属性的白名单。我使用的是rails 4代码,但得到的结果是:唯一约束失败:box.id我已经白名单了所有属性!
def create
  @modification = Modification.new(change_params)

  respond_to do |format|
    if @modification.save

      @modification.entity.boxes.each do |d| 
        @modification.boxes << d.dup
      end

      flash[:success] = "Success"
      format.html { redirect_to @modification }
      format.json { render :show, status: :created, location: @modification }
    else
      format.html { render :new }
      format.json { render json: @modification.errors, status: :unprocessable_entity }
    end
  end
end