SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

Ruby on Rails + Curl(AD)

Ruby on Rails + Curl
リッチクライアントCRUDアプリを作成する

第2回

  • このエントリーをはてなブックマークに追加

JSONフォーマット出力機能の追加

 JSONフォーマットでの出力ができるようにコントローラーを改造してみましょう。respond_toブロックのformat.xmlの行をコピーし、xmlをjsonに書き換えるだけです。

app/controllers/players_controller.rb
class PlayersController < ApplicationController
 
  def chart
    @players = Player.all
    render :layout => false, :content_type => 'text/vnd.curl'
  end
  
  def index
    @players = Player.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml  => @players }
      format.json { render :json => @players } # 追加
    end
  end

  def show
    @player = Player.find(params[:id])
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml  => @player }
      format.json { render :json => @player } # 追加
    end
  end

  def new
    @player = Player.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml  => @player }
      format.json { render :json => @player } # 追加
    end
  end

  def edit
    @player = Player.find(params[:id])
    respond_to do |format|
      format.html # edit.html.erb
      format.xml  { render :xml  => @player }
      format.json { render :json => @player } # 追加
    end
  end

  def create
    @player = Player.new(params[:player])

    respond_to do |format|
      if @player.save
        flash[:notice] = 'Player was successfully created.'
        format.html { redirect_to(@player) }
        format.xml  { render :xml  => @player, :status => :created, :location => @player }
        format.json { render :json => @player, :status => :created, :location => @player } # 追加
      else
        format.html { render :action => "new" }
        format.xml  { render :xml  => @player.errors, :status => :unprocessable_entity }
        format.json { render :json => @player.errors, :status => :unprocessable_entity } # 追加
      end
    end
  end

  def update
    @player = Player.find(params[:id])

    respond_to do |format|
      if @player.update_attributes(params[:player])
        flash[:notice] = 'Player was successfully updated.'
        format.html { redirect_to(@player) }
        format.xml  { head :ok }
        format.json { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml  => @player.errors, :status => :unprocessable_entity }
        format.json { render :json => @player.errors, :status => :unprocessable_entity } # 追加
      end
    end
  end

  def destroy
    @player = Player.find(params[:id])
    @player.destroy

    respond_to do |format|
      format.html { redirect_to(players_url) }
      format.xml  { head :ok }
      format.json { head :ok } # 追加
    end
  end
end

 さて、出力されるJSONですが、http://localhost:3000/players/957451028.jsonの結果は次のように、クラス名 : 値のハッシュになっています。このうちクラス名については、あると便利な場合もありますが、今回は扱うクラスはplayerだけなので余分なデータとなってしまっています。

{"player": {"name": "RADUNSKE,Brock", "no": 25, "goal": 29, 
"created_at": "2009-05-06T02:27:14Z", "updated_at": "2009-05-06T02:27:14Z",
"id": 957451028, "team": "AHL", "assist": 28}}

 そこで、config/environment.rbファイルに以下の行を追加し、サーバを再起動してみましょう。

ActiveRecord::Base.include_root_in_json = false

 今度は、http://localhost:3000/players/957451028.jsonの結果は以下のように値のハッシュのみになりました。

{"name": "RADUNSKE,Brock", "no": 25, "goal": 29, "created_at": "2009-05-06T02:27:14Z",
"updated_at": "2009-05-06T02:27:14Z", "id": 957451028, "team": "AHL",
"assist": 28}
app/controllers/application_controller.rb

 なお、Ruby on RailsはデフォルトでCSRF(Cross Site Request Forgeries)対策用機能が動いていますが、リッチクライアントで使う場合は思わぬところでエラーになってしまう場合があります。そのため、今回は CSRF対策用機能を無効にしています(本当のアプリを作成する場合はむやみに無効にしないでくださいね)。

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  # 以下の行をコメントアウト
  #protect_from_forgery # See ActionController::RequestForgeryProtection for details

  ・・・ 以下省略  ・・・

次のページ
データ一覧の表示

この記事は参考になりましたか?

  • このエントリーをはてなブックマークに追加
Ruby on Rails + Curl連載記事一覧

もっと読む

この記事の著者

吉田裕美(ヨシダユウミ)

有限会社 EY-Office 取締役CADのベンチャー企業でCADのコア部分や図面管理システムなどの開発に従事した後、独立しJava,Ruby,PerlでWebアプリを中心に開発してきた。現在は殆どの開発はRuby on Rails。ここ数年はソフトウェアエンジニアの教育に興味をもち、従来の知識偏重な教育ではなく現実の問題を解決できるエンジニアを育てる教育に注力している。またLisp等に関心...

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

【AD】本記事の内容は記事掲載開始時点のものです 企画・制作 株式会社翔泳社

この記事は参考になりましたか?

この記事をシェア

  • このエントリーをはてなブックマークに追加
CodeZine(コードジン)
https://codezine.jp/article/detail/4112 2009/06/30 15:00

おすすめ

アクセスランキング

アクセスランキング

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー

アクセスランキング

アクセスランキング