2017-04-13 48 views
0

我有这3种模式,主题和帖子处于多对多关系。如何在JSON结果中包含关联模型?

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: [ ... ] 
} 

我已经使用了包括方法,包括联想,但我当使用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" 
    } 
] 

不包括应该把相关的记录返回的对象里面的方法?

回答

1

是,include会将相关记录,但你在错误的地方使用它,试试这个:

def index 
    @posts = Post.all 
    json_response(@posts.as_json(include: :topics)) 
end 

检查here以获取更多信息。