【发布时间】:2013-07-19 20:36:59
【问题描述】:
我正在使用 ActiveModel::Serializers 构建 API。使用参数有条件地侧载数据的最佳方法是什么?
所以我可以提出像GET /api/customers这样的请求:
"customers": {
"first_name": "Bill",
"last_name": "Gates"
}
还有GET /api/customers?embed=address,note
"customers": {
"first_name": "Bill",
"last_name": "Gates"
},
"address: {
"street": "abc"
},
"note": {
"body": "Banned"
}
类似的东西取决于参数。我知道 ActiveModel::Serializers 有 include_[ASSOCIATION]? 语法,但我怎样才能从我的控制器中有效地使用它?
这是我目前的解决方案,但并不整洁:
customer_serializer.rb:
def include_address?
!options[:embed].nil? && options[:embed].include?(:address)
end
application_controller.rb:
def embed_resources(resources = [])
params[:embed].split(',').map { |x| resources << x.to_sym } if params[:embed]
resources
end
customers_controller.rb:
def show
respond_with @customer, embed: embed_resources
end
一定是更简单的方法吗?
【问题讨论】:
标签: ruby-on-rails json api active-model-serializers