Skip to content

Instantly share code, notes, and snippets.

@mfdeveloper
Last active August 29, 2015 14:15
Show Gist options
  • Save mfdeveloper/9bd708b1d2ee985799e2 to your computer and use it in GitHub Desktop.
Save mfdeveloper/9bd708b1d2ee985799e2 to your computer and use it in GitHub Desktop.
Rails - Model with a findAll using multiple conditions
class MyModel < ActiveRecord::Base
attr_acessible :name, :value, :role_id
# Another strategy: multiple conditions with
# multiple ActiveRecord::Relation#where() method calls
def recipients(offset=0, limit=100, data = {})
result = self.order(:id).offset(offset).limit(limit).where('value IS ?', nil)
if data.is_a?(Hash) and !data.empty?
result = result.where('LOWER(name) LIKE ?', '%'+data[:name].downcase+'%') if data[:name]
result = result.where(role_id: data[:roles]) if data[:roles]
end
result
end
end
@viniciustorves
Copy link

o que eu mudaria:

transformaria esse bloco em um metodo, para evitar if. if, if... e colocaria o retorno dele sendo uma array, lá no metodo .

if data.is_a?(Hash) and !data.blank?
if data[:name]
conditions[:key] += ' AND LOWER(name) LIKE :name'
conditions[:value][:name] = "%#{data[:name].downcase}%"
end
if data[:roles]
conditions[:key] += ' AND role_id IN (:roles)'
conditions[:value][:roles] = data[:roles].join(',')
end

end

all(:order => :id, :offset => offset, :limit => limit, :conditions => [conditions[:key],conditions[:value]]

você pode remover o bloco [[conditions[:key],conditions[:value]], atribuir a uma variavel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment