我有两个资源- post
和author
。post
有一个author
。当我获取文章的详细信息时,我想有选择地包括作者的细节。
例子-
GET /authors/1
{
'id': 1,
'name': 'Some name',
'email': 'admin@example.com',
'address': 'Some address',
'mobile': '',
'language': 'ruby'
}
GET /posts/1
我想要-
{
'id': 1,
'created_at': '2017-01-01 10:00:00',
'views': 7500,
'seo_score': 4,
'author': {
'id': 1,
'name': 'Some name',
'email': 'admin@example.com'
}
}
而不是,
{
'id': 1,
'created_at': '2017-01-01 10:00:00',
'views': 7500,
'seo_score': 4,
'author': {
'id': 1,
'name': 'Some name',
'email': 'admin@example.com',
'address': 'Some address',
'mobile': '',
'language': 'ruby'
}
}
include
、exclude
、only
等在序列化程序中选择性地选择关联的属性。发布于 2017-11-29 21:18:57
您可以创建与所选列的新关联,如下所示
belongs_to :author_with_partial_details, -> { select [:id, :name, :email] }, :class_name => "Author"
然后用它像这样
Post.find(params[:id]).includes(:author_with_partial_details)
或者,您也可以使用jbuilder来创建自己的JSON结构,下面是到https://github.com/rails/jbuilder的链接
https://stackoverflow.com/questions/47566300
复制相似问题