LoginSignup
0
0

More than 3 years have passed since last update.

組み合わせ爆発を回避せよ!Rails初心者エンジニアの工夫

Posted at

初心者である私はif~elseの形に慣れ過ぎていた

最初は下記のように書いていた。(statusは絶対に値が入っているので1では省略)

1

if params[:title].present?
 if params[:price_gteq].present? && params[:price_lt].present?
   @products = Product.where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}").where(status: params[:status]).where(title: params[:title])
 else
  @products = Product.where(title: params[:title])
 end
else
 if params[:price_gteq].present? && params[:price_lt].present?
  @products = Product.where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}").where(status: params[:status]).where(title: params[:title])
 else
  @products = Product.all
 end
end

もっと簡単にかけるくない?と思いelseを抜いた。しかしまだゴールではない

2

@products = Product.all
    @products = Product.where(status: params[:status]).where(title: params[:title]) if params[:title].present?
    @products = Product.where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}").where(status: params[:status]) if params[:price_gteq].present? && params[:price_lt].present?
    @products = Product.where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}").where(status: params[:status]).where(title: params[:title])if params[:price_gteq].present? && params[:price_lt].present? && params[:title].present?

まだまだ綺麗にかけるぞ!と思い、さらに絞り込む。ここで考えないといけないのが
ActiveRecord::Relationは、where などで演算した後も ActiveRecord::Relation を返すということ
一瞬はてなマークが頭に浮かぶと思います。簡単にいうと、whereなどのActiveRecord::Relationは同じ型を返し続ける性質があるという。

そのことを踏まえて書いたコードがこちら(ゴール)

3


@products = Product.all
    @products = @products.where(title: params[:title]) if params[:title].present?
    @products = @products.where(status: params[:status]) if params[:status].present?
    @products = @products.where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}") if params[:price_gteq].present? && params[:price_lt].present?


###3番のゴールは雰囲気はこれと同じ。三番はこれを場合分けしている###
@products = @products.where(title: params[:title]).where(status: params[:status]).where("price>=? AND price<=?", "#{params[:price_gteq]}", "#{params[:price_lt]}")

今回のポイント

  1. 条件分岐は「存在するときだけ発動する」みたいなニュアンス
  2. ActiveRecord::Relationは同じ型を返し続ける
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