mysql - How should I write case statement depend of parameters key? -
for example have index action:
def index if params[:query] @pharmaceutics = pharmaceutic.where("name ?", params[:query]) elsif params[:code] @pharmaceutics = pharmaceutic.where("barcode ?", params[:code]) else @pharmaceutics = pharmaceutic.all end end
and when send 2 params: code , query filter pharmaceutics using both of them. have mysql database.
i use scoped
method, this:
def index scope = pharmaceutic.scoped # pharmaceutic.all if use rails 4 scope = scope.where('name ?', params[:query]) if params[:query].present? scope = scope.where('barcode ?', params[:code]) if params[:code].present? @pharmaceutics = scope end
you can write custom scopes , replace where(...)
them make code clearer.
Comments
Post a Comment