简体   繁体   English

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

[英]Rails 5 Use nested attributes to link polymorphic association

I got 3 models, schema like below: 我有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

UPDATE, controller is here: 更新,控制器在这里:

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

First, create a Graphic instance in an action, then got graphic.id = 1 . 首先,在操作中创建一个Graphic实例,然后得到graphic.id = 1
Then, create SampleA or SampleB , parameters like { graphic_attributes: { id: 1 } } 然后,创建SampleASampleB ,像{ graphic_attributes: { id: 1 } }

But it throw 404 exception out, without any SQL query like select * from graphics where id = 1 . 但是它抛出404异常,而没有任何SQL查询,例如select * from graphics where id = 1

Do I miss anything? 我想念什么吗?
And how could I link the SampleA (or SampleB) to an existing Graphic when creating. 在创建时如何将SampleA(或SampleB)链接到现有图形。

Very apperciate. 非常赏识。

When you provide 'id' in nested attributes, rails tries to find in the database a Graphic with a given id, which belongs to given sample already , and update this record. 当您在嵌套属性中提供“ id”时,rails会尝试在数据库中找到具有给定id( 已属于给定样本)的Graphic,并更新此记录。

You can connect association just like this: 您可以像这样连接关联:

graphic.imageable = sample_obj
graphic.save

or 要么

sample_obj.graphic = graphic
sample_obj.save

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM