LoginSignup
39
29

More than 5 years have passed since last update.

Jbuilderのpartialを使ってDRYにjsonを書く

Posted at

jbuilderを使っていると、各アクションで重複する情報を扱わなければならない場面がしばしばある。そういうとき、partial!でテンプレートを呼び出す。

_article.json.jbuilder
json.extract! article, :id, :amount
json.url article_url(article)
index.json.jbuilder
# @articles = Article.all
json.articles @articles do |article|
  json.partial! article
end
show.json.jbuilder
json.article do
  json.partial! @article
end

すっきり。

39
29
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
39
29