34
13

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 1 year has passed since last update.

#Rails の ActiveRecord の OR条件をつなげる時は、 joins などの構造が矛盾せず、一致していなければいけないらしい!

Last updated at Posted at 2019-07-02

このエラー何?

User
  .left_joins(:books)
  .where.not(books: {user_id: nil}).or(
	User
	  .left_joins(:lovers)
	  .where.not(lovers: {user_id: nil})
  )
 ( ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:left_outer_joins] )

メインの方にも、ORの方にも、両方に全く同じ joins をつけなければいけないみたいだ!

なんか冗長だよね?でも、そうなんだよ。

User
  .left_joins(:books)
  .left_joins(:lovers)
  .where.not(books: {user_id: nil}).or(
	User
	  .left_joins(:books)
	  .left_joins(:lovers)
	  .where.not(lovers: {user_id: nil})
  )

Scope とかにまとめておくと良いかもしれないね!

class User < ApplicationRecord
...
  scope :useful_joins, -> do
    .left_joins(:books)
    .left_joins(:lovers)
  end
end
User
  .useful_joins
  .where.not(books: {user_id: nil}).or(
    User
      .useful_joins
	  .where.not(lovers: {user_id: nil})
  )

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

34
13
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
34
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?