2017-06-02 108 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