17. 2.ActiveResource をつかって食べログAPIを表示する
rbc_tabelog/app/models/restaurant.rb をさらに変更
class Restaurant < ActiveResource::Base
API の URL を設定
self.site = quot;http://api.tabelog.com/quot;
def self.find_restaurants(restautant_params = {})
restautant_params[:Key] = quot;96448b290b6556976f047110914fcf91e88c38b9quot;
Hash.from_xml(
self.find( 食べログAPIのキーを設定します。
:one, ご自分のキーを持っている方は、こちらに入力
:from => quot;/Ver2.1/RestaurantSearch/quot;,
:params => restautant_params
検索メソッドを作成
).to_xml
今回は引数をハッシュで渡します
)
end
Hash.from_xmlでxmlをハッシュに(無理矢理)変換しています。
end
これで model は完成!
17
18. 2.ActiveResource をつかって食べログAPIを表示する
次は rbc_tabelog/app/controllers/restaurant_controller.rb
先ほどモデルで作ったメソッドを呼び出します
赤字部分を変更していきます
class RestaurantsController < ApplicationController
# GET /restaurants
# GET /restaurants.xml
def index
@restaurants = Restaurant.find_restaurants(request.query_parameters)[quot;restaurantquot;]
respond_to do |format|
request.query_parameters
format.html # index.html.erb
リクエストパラメータを引数にします
format.xml { render :xml => @restaurants }
end
end
・・・・・・
end
今回は index 以外は使わないので削除しましょう(コメントアウトでもいいよ)
最終行の end も削除してしまわないように注意
18