ruby on rails - How to accumulate query condition in active record? -
fast example,
@user = user.all @user = @user.where(live: true) if params[:live] @user = @user.where(another: true) if params[:another] @user = @user.where(another2: true) if params[:another2] @user = @user.where(another3: true) if params[:another3] . . .
this code hitting db lot, if has lots of params
so i'm thinking of saving search condition var , execute @ final this.
where_condition += '.where(live: true)' if params[:live] where_condition += @user.where(another: true) if params[:another] where_condition += @user.where(another2: true) if params[:another2] where_condition += @user.where(another3: true) if params[:another3] . . . @user = user.all.where_condition
is there solution this?
rails uses lazy-evaluation of activerecord relations, therefore code doesn't hit database multiple times once, when query evaluated.
you can check looking @ logs. notice query executed once.
therefore, code fine. still, there couple of improvements can adopt. first 1 use !
method chain conditions.
rather than
@user = user.all @user = @user.where(live: true) if params[:live] @user = @user.where(another: true) if params[:another] ...
you can use
@user = user.all @user.where!(live: true) if params[:live] @user.where!(another: true) if params[:another]
the second one, should avoid build chain of conditions directly in controller, because makes code hard tested. in order test successful execution of query, have build entire controller test.
refactor code out in model method.
class user def self.search(params) scope = scope.where!(live: true) if params[:live] # ... scope end end
in controller
@users = user.search(params)
this make unit testing of model , controller easier can test them independently. code more maintainable on long period.
Comments
Post a Comment