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

More than 5 years have passed since last update.

【Rails】ActiveRecordでor()の中でjoins()を使うとエラーがでる時の対処方法

Posted at

ActiveRecordで検索する際に、外部結合した検索条件と組み合わせると下記のエラーが発生したので、その時の対処法のメモです。

ArgumentError (Relation passed to #or must be structurally compatible. Incompatible values: [:joins]):

エラーになるコード

class Member < ApplicationRecord
  has_many :nicknames

  # ニックネーム部分一致
  scope :nicknames_cont, lambda { |val|
    joins(:nicknames)
    .merge(Nickname.where(ActiveRecord::Base.sanitize_sql_array(['word LIKE ?', "%#{val}%"])))
  }
  # 苗字完全一致 OR ニックネーム部分一致
  scope :freeword_cont, lambda { |val|
    where(last_name: val)
    .or(nicknames_cont(val))
  }
end

class Nickname < ApplicationRecord
  validates :member, presence: true
  validates :word, presence: true
  belongs_to :member
end

Members.freeword_cont('渡辺')

↑これだとエラー

ArgumentError (Relation passed to #or must be structurally compatible. Incompatible values: [:joins]):

修正したコード

.orを呼んでいる元と.orの中の構造を揃える必要があるので
.orを呼んでいる元.orの中共に.joins()を呼ぶと解決します!

members.rb
class Member < ApplicationRecord
  has_many :nicknames
  # ニックネーム部分一致
  scope :nicknames_cont, lambda { |val|
    joins(:nicknames)
    .merge(Nickname.where(ActiveRecord::Base.sanitize_sql_array(['word LIKE ?', "%#{val}%"])))
  }
  # 苗字完全一致 OR ニックネーム部分一致
  scope :freeword_cont, lambda { |val|
    where(last_name: val)
    .joins(:nicknames) # こいつを追加
    .or(nicknames_cont(val))
  }
end
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?