【问题标题】:Controller not making associations in Rails because of wrong format由于格式错误,控制器没有在 Rails 中建立关联
【发布时间】:2015-12-15 13:05:26
【问题描述】:

我需要为Modification 模型if.save 建立新的关联。这些关联也需要与相关的Entity 模型相同。但我收到了这个错误:

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

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

更多信息:

每个Modification都属于Entity ModificationsEntities has_many Boxes

【问题讨论】:

  • boxes 是一个关联吗?如果是这样,dBox,所以这样做@modification.boxes.new(d) 会产生你提到的错误消息。
  • 是的。盒子就是联想。
  • @modification.boxes << d 你可以做
  • 或者,可能是@modification.boxes.create!(d.attributes)(至少在rails 3中)

标签: ruby-on-rails ruby controller associations


【解决方案1】:

所以您想使用现有的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

【讨论】:

  • 现在收到此错误:UNIQUE 约束失败:boxes.id
  • 好的,嗯...你包括.except(:id)位吗??
  • 我应该把这段代码的一部分放在Private吗?因为现在我收到此错误:ActiveModel::ForbiddenAttributesError。是的,我包括.except(:id)
  • 好的,你需要使用 Rails 4 代码。我刚刚更新了它...我忽略了属性的白名单。
  • 我正在使用 rails 4 代码,但得到这个:唯一约束失败:boxes.id 我已将所有属性列入白名单!
【解决方案2】:

当你声明一个has_many关联时,声明类会自动获得16个关联相关的方法作为提及Guide Ruby On Rails Association Has-Many

  def create

    @modification = Modification.new(change_params)
    respond_to do |format|
      if @modification.save

        @modification.entity.boxes.each do |d| 
          @modification.boxes << d # if d.present? use if condition there is nay validation in your model.
        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

希望这个你好!!!

【讨论】:

  • 看起来不错,但它为已制作的 Box 建立了新的关联。我需要制作全新的盒子。我该怎么做?
  • 能否请您添加更多association_info关于具有的模型
猜你喜欢
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多