Ruby on rails Rails:在jbuilder中隐藏内部对象的属性,并显示多个';jbuilder中的s属性
我已经为一篇文章生成了以下JSON:Ruby on rails Rails:在jbuilder中隐藏内部对象的属性,并显示多个';jbuilder中的s属性,ruby-on-rails,json,Ruby On Rails,Json,我已经为一篇文章生成了以下JSON: { "comments":[ { "created_at":"2015-09-07T23:04:46.000Z", "id":2, "post_id":32, "text":"sdfsdfdsf", "updated_at":"2015-09-07T23:04:46.000Z", "user_id":13 }
{
"comments":[
{
"created_at":"2015-09-07T23:04:46.000Z",
"id":2,
"post_id":32,
"text":"sdfsdfdsf",
"updated_at":"2015-09-07T23:04:46.000Z",
"user_id":13
}
],
"id":32,
"text":"xxxx",
"user":{
"college_id":1,
"created_at":"2015-09-06T21:37:06.000Z",
"email":"mhewedy@hotmail.com",
"gender":"m",
"id":14,
"name":"mhewedy",
"password_digest":"$2a$10$shb6XUFtYnm0ctCPMEb88eDyXmw/jnhDMN65GVPr9Z19DalfOGJzC",
"university_id":4,
"updated_at":"2015-09-07T18:42:10.000Z",
"user_type":"student",
"username":"mhewedy5"
}
}
其中Post
属于用户
,而Post
有许多注释
,其中每个注释都属于用户
(直接)
我想在comments
下显示User
对象,并从Post
和Comment
的User
对象中隐藏password\u digest
字段
我正在使用以下jbuilder文件:
json.array!(@posts) do |post|
json.extract! post, :id, :text, :user, :comments
end
另外,我找不到足够的资源用于jbuilder online。您可以用它来构建嵌套的JSON:
yourJSON = Jbuilder.new do |j|
j.id @post.id
j.text @post.text
#(... other @post attributes ...)
j.user do
j.id @post.user.id
j.email @post.user.email
#(... other @post.user attributes ...)
end
j.comments @post.comments.each do |aComment|
j.id aComment.id
j.text aComment.text
#(... other Comment attributes ...)
end
end
render json: yourJSON.target!
这将生成以下JSON:
{
id:1,
text:"Post text",
//(...)
user: {
id: 30,
email: "user@email.com",
//(...)
},
comments[
{
id:2002
text:"this is the comment text",
//(...)
},
{
id:2003
text:"this is the comment text",
//(...)
},
//(... other comments here ...)
]
}
通过RailsCasts的帮助修复: 在此处观看有关RailsCasts的视频:
没用,你能推荐一些详细的教程吗?我在的帮助下修复了。谢谢你的支持
json.(@posts) do |post|
json.(post, :id, :text, :created_at)
json.comment_count post.comments.size
json.user do |json|
json.(post.user, :id, :name, :gender, :college_id, :university_id, :user_type)
end
end