Ruby 使用 RABL 映射 JSON 多个但不是所有属性
Ruby map JSON multiple but not all attributes with RABL
我有以下Rabl观点:
node(:relations) do |p|
related = p.relations.pluck(:related_to_id)
Spree::Product.find(related)
end
这会呈现以下内容:
"relations": [
{
"product": {
"id": 2,
"name": "T-SHIRT",
"description": "Awesome T shirts"
"created_at": "..."
"updated_at: "..."
.
.
.
bunch of other columns that I don't need.
我的问题是如何只抓取 :name
和 :description
,以便 JSON 输出看起来像:
"relations": [
{
"product": {
"name": "T-SHIRT",
"description": "Awesome T shirts"
}
]
我试过映射它,Spree::Product.find(related).map { |r| [r.name, r.description] }
但是 returns 只有值,像这样:
"relations": [
"T-SHIRT",
"Awesome T shirts"
]
感谢您的帮助!
更新:
当我写的时候:
child :related_products do
attributes :name, :description
end
我得到:
"spree_relations": [
{}
]
Link 到模型:
https://github.com/spree-contrib/spree_related_products/blob/master/app/models/spree/relation.rb
嗯,可能有多种方法可以做到。
可以使用rails#as_json
方法。
node(:relations) do |p|
related = p.relations.pluck(:related_to_id)
Spree::Product.find(related).as_json(only: [:name, :description])
end
或者你可以尝试用 rabl 的方式来做。
child :related_products do
attributes :name, :description
end
但是为此您可能需要稍微更改一下模型。
我有以下Rabl观点:
node(:relations) do |p|
related = p.relations.pluck(:related_to_id)
Spree::Product.find(related)
end
这会呈现以下内容:
"relations": [
{
"product": {
"id": 2,
"name": "T-SHIRT",
"description": "Awesome T shirts"
"created_at": "..."
"updated_at: "..."
.
.
.
bunch of other columns that I don't need.
我的问题是如何只抓取 :name
和 :description
,以便 JSON 输出看起来像:
"relations": [
{
"product": {
"name": "T-SHIRT",
"description": "Awesome T shirts"
}
]
我试过映射它,Spree::Product.find(related).map { |r| [r.name, r.description] }
但是 returns 只有值,像这样:
"relations": [
"T-SHIRT",
"Awesome T shirts"
]
感谢您的帮助!
更新:
当我写的时候:
child :related_products do
attributes :name, :description
end
我得到:
"spree_relations": [
{}
]
Link 到模型:
https://github.com/spree-contrib/spree_related_products/blob/master/app/models/spree/relation.rb
嗯,可能有多种方法可以做到。
可以使用rails#as_json
方法。
node(:relations) do |p|
related = p.relations.pluck(:related_to_id)
Spree::Product.find(related).as_json(only: [:name, :description])
end
或者你可以尝试用 rabl 的方式来做。
child :related_products do
attributes :name, :description
end
但是为此您可能需要稍微更改一下模型。