Associations and collections with a roar

Suppose we have something like:

class Company include Mongoid::Document has_many :users field :name, type: String end class User include Mongoid::Document belongs_to :company field :name, type: String end module CompanyRepresenter include Roar::Representer::JSON property :name end module UserRepresenter include Roar::Representer::JSON property :name link :self do user_url end end 

Then we continue to do something like this:

 user.extend(UserRepresenter).to_json 

And everything is just great. But what about:

 User.all.to_json 

or

 company.extend(CompanyRepresenter).users.to_json? 

or even:

 company.users.collect{|u| u.extend(UserRepresenter)}.extend(Representable::JSON::Collection).to_json 

The result is always an array of regular to_json entries in Mongoid.

The question is how to get something like Company.all.to_json to use Roared JSON, including links and other additional serialization data.

+6
source share
1 answer

Turns out this is achieved by simply using Representable (which is used by the roar):

 require 'roar/representer/json' module PostRepresenter include Roar::Representer::JSON property :id property :title end require 'representable/json/collection' module PostsRepresenter include Representable::JSON::Collection items extend: PostRepresenter end Post.limit(10).extend(PostsRepresenter) 
+8
source

Source: https://habr.com/ru/post/909820/


All Articles