17

ActiveModel::Serializersを使用して API を構築しています。paramsを使用して条件付きでデータをサイドロードする最良の方法は何ですか?

だから私は次のようなリクエストをすることができます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"
}

パラメータによっては、そのようなもの。include_[ASSOCIATION]?ActiveModel::Serializers に構文があることは知っていますが、コントローラーから効率的に使用するにはどうすればよいですか?


これは私の現在の解決策ですが、きちんとしていません:

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

もっと簡単な方法である必要がありますか?

4

3 に答える 3

2

同様の機能が欲しかったので、あなたの回答に基づいてさらに別の解決策があります。ドキュメントによると、関連付けのシリアライゼーションの下位レベルの制御が必要な場合は、オーバーライドできますinclude_associations!

例えば:

def include_associations!
    if scope[:embed]
        include! :addresses, {embed: :ids, include: true}
    else
        include! :addresses, {embed: :ids}
    end
end
于 2013-11-14T01:19:38.717 に答える
1

include_associations について知っておくととても役に立ちます! ありがとう! active_model_serializers gem (バージョン 0.8.3) を使用@optionsすると、コントローラーでコンテキストを設定できることに注意してください。たとえば、コントローラーで呼び出す場合

render json: customer, include_addresses: true

次に、CustomerSerializer で:

has_many :addresses
def include_associations!
  if @options[:include_addresses]
    include! :addresses
  end
end

次に、アドレスがシリアル化されます。include_addressesに設定してレンダリングするとfalse、そうではありません。active_model_serializers の新しいバージョンでserialization_optionsは、@options.

于 2015-03-01T18:04:11.970 に答える