Come l'accesso ': has_many: attraverso' unire i dati della tabella quando si utilizza to_json?
-
26-09-2019 - |
Domanda
Ho tre modelli (semplificati qui):
class Child < ActiveRecord::Base
has_many :childviews, :dependent => :nullify
has_many :observations, :through => :childviews
end
class Childview < ActiveRecord::Base
belongs_to :observation
belongs_to :child
end
class Observation < ActiveRecord::Base
has_many :childviews, :dependent => :nullify
has_many :children, :through => :childviews
end
Sto inviando questo per un po 'di JavaScript utilizzando il metodo to_json Rails' in questo modo:
render :layout => false , :json => @child.to_json(
:include => {
:observations => {
:include => :photos,
:methods => [:key, :title, :subtitle]
}
},
:except => [:password]
)
Questo funziona perfettamente. Le osservazioni vengono recuperati bene 'attraverso' la tabella di join (childviews).
Tuttavia , voglio anche per arrivare a dati che si trova nel childviews join tabella; in particolare il valore per 'needs_edit'.
Non riesco a capire come ottenere a questi dati in una chiamata to_json.
chiunque aiutareCan me? Molte grazie in anticipo.
qryss
Soluzione
Non è sicuro, ma non dovrebbe questo lavoro?
@child.to_json(
:include => {
:observations => {
:include => :photos,
:methods => [:key, :title, :subtitle]
},
:childviews => { :only => :needs_edit }
},
:except => [:password]
)
EDIT: Questo lavoro potrebbe, in quanto anche childviews belongs_to l'overvation:
@child.to_json(
:include => {
:observations => {
:include => { :photos, :childviews => { :only => :needs_edit } }
:methods => [:key, :title, :subtitle]
}
},
:except => [:password]
)
Altri suggerimenti
Grazie per Rock per i puntatori - ora ho che funziona
Il codice:
@child.to_json(:include =>
{
:observations => {
:include => {
:photos => {},
:childviews => {:only => :needs_edit}
},
:methods => [:S3_key, :title, :subtitle]
}
},
:except => [:password]
)
mi dà questa uscita (abbreviato per chiarezza):
{
"child":
{
"foo":"bar",
"observations":
[
{
"foo2":"bar2",
"photos":
[
{
"foo3":"bar3",
}
],
"childviews":
[
{
"needs_edit":true
}
]
}
]
}
}
Grazie, Rock! Che stava facendo la testa.
:)
qryss