1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】ポリモーフィック関連先の項目で検索する方法

Last updated at Posted at 2021-07-14

はじめに

ポリモーフィック関連先の項目の検索方法を時間をかけて調べたのですが、なかなか出てこなかったためまとめておこうかなと思います。

ポリモーフィック関連の作成方法などはやりません。
関連リンクを下記に載せておくので、必要であれば参考にしてください。。

関連性

以下のようなAnimalモデル、Pandaモデル、Catモデルの構成を作成します。

animal.rb
class Animal < ApplicationRecord
  belongs_to :animalable, polymorphic: true
end
panda.rb
class Panda < ApplicationRecord
  has_many :animal, as: :animalable, dependent: :destroy
end
cat.rb
class Cat < ApplicationRecord
  has_many :animal, as: :animalable, dependent: :destroy
end

ポリモーフィック関連先の項目の検索方法

手順としては、以下となります。

  1. AnimalモデルにPandaモデルをJOIN
  2. where句で検索を実行

まずは、Pandaモデルの例を見ていきます。

# join SQL
join_sql = <<-"EOS"
  JOIN pandas
    ON pandas.id = animals.animalable_id
    AND animals.animalable_type = 'Panda'
EOS

animals = Animal.joins(join_sql)
# search SQL
animals.where("pandas.name LIKE '%ran%'")

次にCatモデルです。まぁ同じですが。。

# join SQL
join_sql = <<-"EOS"
  JOIN cats 
    ON cats.id = animals.animalable_id 
    AND animals.animalable_type = 'Cat'
EOS

animals = Animal.joins(join_sql)
# search SQL
animals.where("cats.name LIKE '%dora%'")

まとめ

ActiveRecord を使っていろいろと試してみたのですが、期待する動作をしてくれませんでした。
力技であまり良くないんだろうなぁと思いましたが、SQLを直接書きました。
もっといいやり方をご存知の方がいれば、教えていただきたいです。

参考


会社紹介

株式会社 Mosaica
最先端テクノロジーで社会課題を解決し、持続可能な未来を創造する IT カンパニー。
AI ソリューション、クラウド統合、DX 推進、経営コンサルティングなど包括的なサービスでビジネス変革を支援しています。

詳しくは 公式サイト までお気軽にご相談ください。
公式サイト: https://mosaica.co.jp/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?