LoginSignup
0
0

More than 5 years have passed since last update.

関連モデルを取得する際の条件の書き方

Last updated at Posted at 2014-02-06

アソシエーションの挙動のカスタマイズに関するメモ

関連モデルを取得するときの条件式の設定には :conditions を使う。

author.rb
has_many :books, conditions: { author_id: 1 }

ってやると、booksテーブルの情報を取得するときは、author_idカラムが1のものに絞ってからの取得になる。
もちろん中間テーブルを挟んでデータを取得するときにも有効。

関連元のアソシエーションで

book.rb
belongs_to :author, conditions: { author_id: 1 }

ってやっても取れないのに上手く行かなくて悩んだ(ヽ´ω`)
修行します。

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