This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PostSerializer < ActiveModel::Serializer | |
| attributes :id, :title, :details, :author | |
| # Will run n Mongo queries for n posts being rendered. | |
| def author | |
| User.find(object.author_id) | |
| end | |
| end | |
| # This is now a Mongoid document, not an ActiveRecord model. | |
| class User |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| posts = Post.all | |
| author_ids = posts.pluck(:author_id) | |
| authors = User.where(:_id.in => author_ids) | |
| # Somehow pass the author objects to the post serializer and | |
| # map them to the correct post objects. Can't imagine what | |
| # exactly that would look like, but probably not pretty. | |
| render json: posts, pass_some_parameter_maybe: authors |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PostSerializer < ActiveModel::Serializer | |
| attributes :id, :title, :details, :author | |
| def author | |
| object.get_author_lazily | |
| end | |
| end | |
| class Post | |
| def get_author_lazily | |
| # The current post object is added to the batch here, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PostSerializer < ActiveModel::Serializer | |
| attributes :id, :title, :details, :author | |
| def author | |
| object.get_author_lazily do |author| | |
| # Serialize the author after it has been loaded. | |
| ActiveModelSerializers::SerializableResource | |
| .new(author) | |
| .as_json[:user] | |
| end | |
| end |
OlderNewer