Rails 5使用嵌套属性链接多态关联

时间:2017-06-02 17:22:28

标签: ruby-on-rails nested-attributes

我有3个模型,模式如下:

class Graphic < ActiveRecord
  belongs_to :imageable, polymorphic: true, optional: true
end

class SampleA < ActiveRecord
  has_one :graphic, as: :imageable
  accepts_nested_attributes_for :graphic
end

class SampleB < ActiveRecord
  has_one :graphic, as: :imageable
  accepts_nested_attributes_for :graphic
end

更新,控制器在这里:

class SampleAscontroller < ApplicationController
  def create
    sample_a = SampleA.new sample_a_params

    if sample_a.valid? && sample.save
      render json: sample_a and return
    end

    render json: sample_a.errors.full_messages, status: 406
  end

  private

  def sample_a_params
    params.require(:sample_a).permit(
      graphic_attributes: [:id]
    )
  end
end

首先,在操作中创建一个Graphic实例,然后获得graphic.id = 1 然后,创建SampleASampleB等参数,例如{ graphic_attributes: { id: 1 } }

但它抛出了404异常,没有任何SQL查询,如select * from graphics where id = 1

我错过了什么吗? 如何在创建时将SampleA(或SampleB)链接到现有的Graphic。

非常好。

1 个答案:

答案 0 :(得分:0)

当您提供&#39; id&#39;在嵌套属性中,rails尝试在数据库中查找具有给定id的图形,已属于给定样本,并更新此记录。

您可以像这样连接关联:

graphic.imageable = sample_obj
graphic.save

sample_obj.graphic = graphic
sample_obj.save