12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[解決]RailsのSTIでJSONにtypeを含むには

Posted at

たとえば、TopicというモデルがSTI(Single Table Inheritance)の親モデルだとして、その下に、NewsやReleaseがあったとする。

そのTopicをJSONに変換しようとすると、STIのtype属性が削除される。これはto_jsontypeを削除してJSON文字列を作ってしまうから。

これを回避するにはmethodsオプションを使用。

pry(main)> Topic.first.to_json
=> {"id":1,"uri":"http:..."}

pry(main)> Topic.first.to_json(methods[:type])
=> {"id":1,"type":"News","uri":"http:..."}
12
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?