I 3 Modelle bekam, Schema wie unten:Rails 5 Verwenden Sie Attribute verschachtelt polymorphe Assoziation zu verknüpfen
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 ist hier:
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
zunächst eine Graphic
Instanz in einer Aktion erstellen , dann bekam graphic.id = 1
.
Dann erstellen SampleA
oder SampleB
, Parameter wie { graphic_attributes: { id: 1 } }
Aber es 404 Ausnahme heraus werfen, ohne SQL-Abfrage wie select * from graphics where id = 1
.
Vermisse ich etwas?
Und wie könnte ich SampleA (oder SampleB) mit einer vorhandenen Grafik beim Erstellen verknüpfen.
Sehr gut erreichbar.
Sie bitte Ihre Controller-Code teilen. – Gerry
@Gerry Controller-Code aktualisiert. –
Könnten Sie bitte auch die komplette Protokollausgabe hinzufügen? – Gerry