LoginSignup
0

More than 3 years have passed since last update.

whereメソッドを使って別のモデルの値を参考に絞り込みを行う。

Posted at

概要

whereメソッドを使った複数の条件の絞り込みを行ったのでまとめる。

やりたいこと

productモデルが作成された時間の直前に作成されたdeveloperモデルの情報を一つ取得したい。

前提条件

Product(製品)モデルとDeveloper(開発者)を作成。この2つのモデルは関連付けされていない。(ここはあえてです)
Developerモデルはどんな製品を作ったのかの情報(developed_product_number)を持っている。productには製品ナンバー(number)がついておりこの2つの値は等しい。
(だったら関連付けさせようよって話ですが今回はこの条件でいきます。)
同一の製品を作成した複数の開発者の中から製品ができる直前に作成された開発者の値を取得したい。

実装

ではまず実際のコードを載せます。

product = Product.find(params[:id])


@Developer = Developer.where(developed_product_number: product.id).where('created_at < ?', product).order(created_at: :desc).limit(1) 

こんな感じです。解説いきます

product = Product.find(params[:id])

対象となるproductのIDを取得して変数productに代入。
ここで変数@Developerに条件をつけて絞り込み検索をした値を入れます。

@Developer = Developer.where(developed_product_number: product.id).where('created_at < ?', product).order(created_at: :desc).limit(1) 

部分的に分けます。

@Developer = Developer.where(developed_product_number: product.number)

ここでは先程取得した変数productのidを取得しています。

次に値を絞り込みます。

where('created_at < ?', product).order(created_at: :desc).limit(1) 

ここでproductが作成された時間より前に作成された複数の開発者の情報取得し、降順から数えて1つ目の開発者の情報を取得しました。
かなり長くなってしまったのでここのコードはスコープなどに切り分ける必要がありますね。

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