0
0

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 1 year has passed since last update.

【Jbuilder】DBに直接紐付かないモデルクラスのjbuilderの書き方

Posted at

##今まで
partialでファイル指定

user_infos/show.json.jbuilder
json.user_info do
  json.partial! 'user_infos/user_info', user_info: @user_info
end
user_infos/_user_info.json.jbuilder
json.extract! user_info, :id, :name

##これから
DBに直接紐付かないモデルクラスにActiveModel::Modelincludeする。

ActiveModel::Modelをincludeすると、以下のような機能を使えるようになります。

  • モデル名の調査
  • 変換
  • 翻訳
  • バリデーション

今回はActiveModel::Modelがモデル名の調査をしてくれるのでファイル名を指定しなくてもよくなる。

models/user_info.rb
class UserInfo
  include ActiveModel::Model
...
end
user_infos/show.json.jbuilder
json.user_info do
  json.partial! @user_info #省略できる
end
user_infos/_user_info.json.jbuilder
json.extract! user_info, :id, :name

##参考

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?