LoginSignup
1
0

More than 5 years have passed since last update.

モデルを継承して値を取得したい

Last updated at Posted at 2019-05-27

IBeacon(子) < ShopTerminal(親)

モデル間の継承をしたいとする

継承とは

簡単に言うと、親のモデルに定義されている内容は全部子モデルでも使えるよ〜ってこと

値の取得

で、今回親のモデルの内容を子モデルを使って取得したい と言うこと

コントローラでいつものように値を取得したいけどなぜか
beacon = IBeacon.find_by_uuid(params[:uuid])でbeaconの値が[ ]に。
beacon = ShopTerminal.find_by_uuid(params[:uuid])だとちゃんと値はいってるのに。。。

beacons_controller.rb
class Api::BeaconsController < Api::AbstractSystemController

  def show
    return render_error('Please set uuid', 400) unless params[:uuid].present?
    beacon = IBeacon.find_by_uuid(params[:uuid])
    return render_error('beacon not found', 400) unless beacon.present?
    render json: beacon, serializer: IBeaconSerializer, root: nil
  end
end

解決策

親モデルのShopTerminalにtypeカラム(String型)を追加

そして追加されたtypeカラムの中にIBeaconと書くことで上記のコード通り、子モデルでの値の取得ができるようになった!!

今回やったことはSTIと言うらしい

typeという語はテーブルでSTI(Single Table Inheritance)を指定するために予約されている予約語で、この場合以外に使ったらエラーになるので気をつける。

STI(単一テーブル継承)はACtiveRecoredがサポートしている機能です。

参考: Rails4でSTI(単一継承テーブル)を行う

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