Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url Helpers in ActiveModelSerializer 0.10.0?

Tags:

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 
like image 622
Jimmy Baker Avatar asked Sep 24 '15 18:09

Jimmy Baker


2 Answers

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.

like image 178
Brendon Muir Avatar answered Oct 15 '22 23:10

Brendon Muir


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)

like image 27
Drew Avatar answered Oct 16 '22 00:10

Drew