问题
I know this version is still not officially released but I was checking out rc3 today and I noticed that I can no longer use Rails url helpers inside my serializers. In version 0.8.x, I could do the following:
class BrandSerializer < BaseSerializer
attributes :id, :name, :slug, :state
attributes :_links
def _links
{
self: api_v1_company_brand_path(object.company_id, object.id),
company: api_v1_company_path(object.company_id),
products: api_v1_company_brand_products_path(object.company_id, object.id)
}
end
end
But this is a no go in the new version. What's the best way of resolving this so that I can keep my links in my serializer?
Edit: For now I'm doing the following but would love to hear if there's a more idiomatic way.
class BaseSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
回答1:
If you add this to your ApplicationController
or even probably to the controller generating the response:
serialization_scope :view_context
You can then use the view_context
in the serialiser to access the URL helpers (or any view methods really).
Example: view_context.api_v1_company_brand_path(object.company_id, object.id)
I thought this was probably cleaner than including all those URL helpers etc... into the serialiser class.
回答2:
including the library which had been excluded (as you had done) would most definitely be the shortest route (outside of revising the gem itself, in terms of idiomacy)
来源:https://stackoverflow.com/questions/32768046/url-helpers-in-activemodelserializer-0-10-0