1

I have a model

class Banner < ActiveRecord::Base
  validates :title, presence: true, length: { maximum: 50 }
  validates :description, length: { maximum: 200 }

  belongs_to :document

  def img_url
    document.medium_url
  end
end

and serializer

class BannerSerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :img_url, :document_id
end

When I'm using render json: Banner.all, it response correctly (has "img_url" in the responding

{
"banners": [
    {
      "id": 1,
      "title": "This is title of banner",
      "description": "This is long description...",
      "img_url": "http://localhost:3000//system/documents/attachments/000/000/023/medium/one-piece.jpg?1459601536",
      "document_id": 23
    }
  ]
}

But when I want to return with other object by using. example:

render json: {
      banners: Banner.all,
      blogs: Blog.all,
      partners: Partner.all
    }

The responding don't exist "img_url" (it don't use Serializer).

Please help.

7
  • What if you'd use Blog.all.to_json? Commented Apr 3, 2016 at 7:48
  • It don't include img_url too, beside that, the value of banners become to string Commented Apr 3, 2016 at 7:58
  • Ok. what about using as_json? Commented Apr 3, 2016 at 8:02
  • 1
    looking at docs and this link github.com/rails-api/active_model_serializers/issues/1204 something like this should work: ActiveModel::SerializableResource.new(Banner.all).serializable_hash Commented Apr 3, 2016 at 8:11
  • 1
    try render json: BlogSerializer.new(Blog.all) Commented Apr 3, 2016 at 8:24

1 Answer 1

2

Serializer has new method. That you can call it from controllers too.

render json: BlogSerializer.new(Blog.all)

For array, use ArraySerializer. Example:

blogs = ActiveModel::ArraySerializer.new(blogs, each_serializer: ArticleSerializer)
Sign up to request clarification or add additional context in comments.

5 Comments

I have test again, It worked on single value (example: BlogSerializer.new(Blog.all.frist), but list don't work :(. BTW: thanks
probably, u have an issue somewhere. in my project it works.
I have found a solution by using ArraySerializer :) ActiveModel::ArraySerializer.new(blogs, each_serializer: ArticleSerializer) using for array
I have edited your comment, could you review that I can vote this anwer :)
With your help :), Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.