LoginSignup
11
12

More than 5 years have passed since last update.

【Rails】JbuilderでJSONPを返したい

Last updated at Posted at 2014-04-07

JbuilderJSONP非対応なので jpbuilderというgemを使う…のだが,トラップが多く半日ぐらいハマった.

対応手順

gemのインストール

Gemfileにgem 'jpbuilder'追加.

デフォルトのコールバック関数名の設定

initializer(config/initilizers/jpbuilder.rbとか)にデフォルトのコールバック関数名を書く.

config/initilizers/jpbuilder.rb
JPbuilderHandler.default_callback = "myJsCallback"

View側の対応

Viewの.json.jbuilder.json.jpbuilderにリネームする.

(e.g. show.json.jbuildershow.json.jpbuilder

注意点

普通のJSONと使い分けたい場合

デフォルトのコールバック関数名をnilにする.

config/initilizers/jpbuilder.rb
JPbuilderHandler.default_callback = nil

これでパラメータcallbackでコールバック関数名を渡してあげたらJSONP,何も渡さなければJSONが返ってくるようになる.

Jbuilderのpartialを使いたい場合

呼び出し元のファイル(親のファイル)は.json.jpbuilderに, partialのファイル(子のファイル)は.json.jbuilderのままにしてあげないとmissing templateになっちゃう.

蛇足

jpbuilder作者曰く,

I hope that in the future this can somehow be merged into the jbuilder core. However as of today, the project seems dead (20+ issues and last commit almost 5 months ago), so I am not going to put the effort into a pull request just yet.
Using JSONP with Jbuilder => Productively Distracted

だそうです.つらそう.

11
12
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
11
12