如何在JSON结果中包含关联模型?

时间:2017-04-13 22:12:34

标签: ruby-on-rails

我有这3个模型,主题和帖子处于多对多关系中。

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 

当我获取帖子时,我希望JSON对象也包含主题,如下所示:

{
   title: ...,
   body: ...,
   topics: [ ... ]
}

我使用了include方法来包含关联,但是当我使用httpie测试结果时,返回的帖子不包含相关记录。

def index 
    @posts = Post.includes(:topics).all 

    json_response(@posts)
end

这是httpie结果:

[
    {
        "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"
    }
]

不是include方法应该将关联的记录放在返回对象中吗?

1 个答案:

答案 0 :(得分:1)

是的,list<list<Date>> 会放置相关记录,但您在错误的地方使用它,请尝试以下操作:

include

查看here了解详情。