LoginSignup
2
2

More than 5 years have passed since last update.

【メモ】長いSQLと文字連結

Posted at

今回バグの改修をしていて、モデルでめっちゃ長いSQL文(3行くらい)を呼び出していた。
(めちゃめちゃ古いコードなんだろうな・・・・)

もともとのコード

'''
Sample.where('exists(select * from samples where .... and ....) or exists(select * from sample_options where...) or exists(select * from sample_prices where ...)')
'''
みたいな。長いしSQLを直接操作するので、物理削除と論理削除の違いが出ない状態に。

書いたコード

とりあえず、バグなので意図通り動作して欲しい
→論理削除と物理削除の違いが出るようにする

Sample.where('exists(select * from samples where .... and .... and deleted_at = nil) or exists(select * from sample_options where...) or exists(select * from sample_prices where ...)')

でも長すぎてみにくいので、

Sample.where(
 'exists(select * from samples where .... and .... and deleted_at = nil)' +
  ' or exists(select * from sample_options where...)' +
   ' or exists(select * from sample_prices where ...)'
)

というように文字連結を使った。

'aaa' + 'bbb'
=> "aaabbb"

調べてきたときに学んだもの

chomp

Rubyの標準メソッドで、文末の改行コードを削除

rstrip

Rubyの標準メソッドで、文末の空白を削除

gsub

Rubyの標準メソッドで、任意の文字を指定し、置き換える
例えば

文中の空白を全て消したい
(....).gsub(' ', '')

文中の改行コードを全て消したい
(....).gsub('\n', '')

まとめ

チームで開発しているからコードを見やすくするって大切。
ちょっとした工夫だけど、今後もこういうメソッドやリテラルを使っていこう。

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