1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アソシエーション先のカラムでwhere,orderメソッドを使う

Last updated at Posted at 2018-12-22

意外と記事がなく、詰まったので記事にしました。

例えば

class Movie < ApplicationRecord
  has_many :actors
end
class Actor < ApplicationRecord
  belongs_to :movie
end

という関係になっているとき

controller上で
actorのファンがnilでない映画をDBから抽出したいと思ったときは、(雑)

class MoviesController < ApplicationController
  def hoge
    Movie.includes(:actors).where("actors.fan_count not ?", nil)
  end
end

でデータを抽出できます。

actorのファンが多い順に映画を並べたいときは、

class MoviesController < ApplicationController
  def hoge
    Movie.includes(:actors).order("actors.fan_count")
  end
end

で並べられます。

「重要」

それぞれ指定しているのは

.メソッド("テーブル名.カラム名")

になります。

自分の場合、名前の語尾がxのindexモデルを作ったときに、rails側でテーブル名がindicesとなり、なかなか指定できずにずっとエラーになってしまいました。;;
(ORマッパー頼りでSQL読めないなんて言えない・・・)

しっかりと指定したいアソシエーション先のテーブル名を確認し、指定してあげるようにしましょう。

「補足」

actorのファンがnilでない映画をDBから抽出したいと思ったときは、

こちらは

class MoviesController < ApplicationController
  def hoge
    Movie.includes(:actors).where(:actors {fan_count: :nil})
  end
end

とシンボルで記述できます。

orderでdescの並べ替えをしたいときは上の文のnilをdescにしても上手くいかなかったので(出来ない?)、descのときは文字列""で記述してあげましょう

その他

基本的な記述はリファレンスを参考にしましょう
whereリファレンス
orderリファレンス

Matzもシンボルを廃止しようとしていたしい(笑)
We tried & failed.(Matz)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?