2017-06-02 50 views
1

我有3种型号,架构如下图所示:导轨5使用嵌套属性链接态关联

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,控制器是在这里:

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)链接到现有的图形。

非常无礼。

+1

请分享你的控制器代码。 – Gerry

+0

@Gerry控制器代码已更新。 –

+0

你能否也请添加完整的日志输出? – Gerry

回答

0

当您在嵌套属性中提供'id'时,rails会尝试在数据库中查找给定ID为的图形,该图形属于给定样本,并更新此记录。

您可以连接关联就像这样:

graphic.imageable = sample_obj 
graphic.save 

sample_obj.graphic = graphic 
sample_obj.save