Last active
August 29, 2015 14:15
-
-
Save mfdeveloper/9bd708b1d2ee985799e2 to your computer and use it in GitHub Desktop.
Rails - Model with a findAll using multiple conditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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