3
0

More than 3 years have passed since last update.

ActiveResourceを使ってRailsアプリ同士をAPI連携させる

Posted at

ActiveResourceを使う機会があったので、使い方を備忘録として残します。

ActiveResource とは

簡単に言うと、Railsアプリケーション同士を簡単にAPI連携させる機能です。

フロントとバックを分けて実装したい時に使います。

バック側の実装

実装
apiモードでアプリケーションを作成しています。

$ rails new back --api
$ cd back
$ bin/rails g scaffold bookmark title:string url:string comment:text
$ rake db:migrate

起動

$ rails s

フロント側の実装

実装

DBは使わないのでmigrationを削除しています。

$ rails new front
$ cd front
$ bin/rails g scaffold bookmark title:string url:string comment:text
$ rm -f db/migrate/* 

モデルクラス (app/models/bookmark.rb) を書き換える。
親クラスをActiveResource::Baseに変えて、連携先にhttp://localhost:3000/を指定しています。

app/models/bookmark.rb
class Bookmark < ActiveResource::Base
  self.site = 'http://localhost:3000/'
end

Gemを追加。

Gemfile
gem ‘activeresource'
$ bundle install
# 起動
$ rails s -p 3001 #ポートは3001に指定

動作確認

以上で実装、連携は完了です。

ブラウザで "http://localhost:3001/bookmarks" にアクセスして、いくつかブックマークを追加してみましょう。

<参考>
http://webos-goodies.jp/archives/how_to_use_activeresource_1.html

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