Bowtch Bowtch - 1 year ago 97
Ruby Question

Check and assign to a variable without executing twice ruby

I want to assign a value from a query mongoid to a variable only if the count is superior to a certain value.

if i do

mdl = Mdl.by_params(params) unless Mdl.by_params(params) < limit

The query is executed twice, how do i do to check and assign with one query ?

Answer Source

You have to retrieve the data from Mongoid to do the comparison.

mdl_temp = Mdl.by_params(params)
mdl = mdl_temp unless mdl_temp < limit
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download