我使用ActiveModel :: Serializers來構建API。使用params有條件地加載數據的最佳方法是什麼?有條件地使用ActiveModel :: Serializer進行側載
所以我可以請求像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"
}
類似的東西取決於PARAMS。我知道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
必須是一個更簡單的方法?
我喜歡你的建議,使用view_context。是否有可能使用rspec進行單元測試? – Richard
我已更新我的問題,向您展示我是如何一直這樣做的。 – Richard
明智的答案,謝謝@lou。十分優雅。 – tristanm