Ich habe diese 3 Modelle, Thema und Post sind in einer Viele-zu-Viele-Beziehung.Wie kann man assoziierte Modelle in das JSON-Ergebnis einbeziehen?
class Topic < ApplicationRecord
has_many :post_topic
has_many :posts, through: :posts_topics
validates :name, presence: true, length: { in: 3..26 }, uniqueness: true
end
class Post < ApplicationRecord
has_many :post_topic
has_many :topics, through: :post_topic
validates :title, presence: true, length: { in: 3..255 }
validates :body, presence: true, length: { in: 3..1400 }
accepts_nested_attributes_for :topics, allow_destroy: true
end
class PostTopic < ApplicationRecord
self.table_name = "posts_topics"
belongs_to :post
belongs_to :topic
end
Wenn ich die Beiträge holen, möchte ich das JSON-Objekt Themen haben auch enthalten, etwa so:
{
title: ...,
body: ...,
topics: [ ... ]
}
ich verwendet habe, das Verfahren den Verband aufzunehmen enthält, aber wenn ich Hat httpie verwendet, um das Ergebnis zu testen, enthalten die zurückgegebenen Posts nicht die zugehörigen Datensätze.
def index
@posts = Post.includes(:topics).all
json_response(@posts)
end
Hier ist das httpie Ergebnis:
[
{
"body": "bar",
"created_at": "2017-04-13T00:29:51.506Z",
"id": 1,
"title": "foo",
"updated_at": "2017-04-13T00:29:51.506Z"
},
{
"body": "bar",
"created_at": "2017-04-13T21:20:21.854Z",
"id": 2,
"title": "foo",
"updated_at": "2017-04-13T21:20:21.854Z"
},
{
"body": "bar",
"created_at": "2017-04-13T21:22:02.979Z",
"id": 3,
"title": "foo",
"updated_at": "2017-04-13T21:22:02.979Z"
}
]
Ist das nicht das enthält Verfahren sollte die zugehörigen Datensätze innerhalb des Rückgabeobjekts setzen ??