Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decorated attributes inaccessible in to_json #97

Closed
danielstocks opened this issue Dec 13, 2011 · 5 comments
Closed

Decorated attributes inaccessible in to_json #97

danielstocks opened this issue Dec 13, 2011 · 5 comments

Comments

@danielstocks
Copy link

Hello, thanks for outstanding work on draper. I'm having a small issue:

Background:

class ArticleDecorator < ApplicationDecorator
  decorates :article
  PUBLIC_VISIBLE_ATTRIBUTES = [:title]

  def title
    "hello world"
  end

  def to_json
    attr_set = PUBLIC_VISIBLE_ATTRIBUTES
    article.to_json(:only => attr_set)
  end
end

Problem:

a = AricleDecorator.decorate(Article.first)
a.title # => "hello world"
a.to_json # => "{"title": "old title"}"

Am I doing this wrong?

@vizjerai
Copy link
Contributor

Yes, because your calling article's to_json method directly through the decorator's to_json method where it doesn't know anything about the decorator.

class ArticleDecorator < ApplicationDecorator
  decorates :article

  def title
    "hello world"
  end

  def as_json(*args)
    {
      :title => title
    }
  end
end
a = ArticleDecorator.first
a.title # => "hello world"
a.to_json # => '{"title": "hello world"}'

@danielstocks
Copy link
Author

That explains it, thanks.

@mpelzsherman
Copy link

Thanks, this helped me as well!

@barelyknown
Copy link

This was helpful. Thanks. It would be nice to have a to_json method for decorators that merged the decorator and active record objects so that you could use to_json shortcuts to build the hash.

@steveklabnik
Copy link
Member

It would be nice to have a to_json method for decorators that merged the decorator and active record objects so that you could use to_json shortcuts to build the hash.

Any and all feature suggestions welcome as pull requests. ;) however, you may want to check out https://github.com/josevalim/active_model_serializers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants