trabajo-afectivo/app/models/organization.rb

36 lines
1.1 KiB
Ruby
Raw Normal View History

class Organization < ApplicationModel
2012-04-10 14:06:46 +00:00
has_and_belongs_to_many :users
validates :name, :presence => true
2013-05-21 22:30:09 +00:00
def self.search(params)
# get params
query = params[:query]
limit = params[:limit] || 10
current_user = params[:current_user]
# enable search only for agents and admins
return [] if !current_user.is_role('Agent') && !current_user.is_role('Admin')
# do query
organizations = Organization.find(
:all,
:limit => limit,
2013-05-22 01:40:24 +00:00
:conditions => ['name LIKE ? OR note LIKE ?', "%#{query}%", "%#{query}%"],
2013-05-21 22:30:09 +00:00
:order => 'name'
)
2013-05-22 01:40:24 +00:00
# if only a few organizations are found, search for names of users
if organizations.length <= 3
organizations = Organization.select('DISTINCT(organizations.id)').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').find(
:all,
:limit => limit,
:conditions => ['users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"],
:order => 'organizations.name'
)
end
2013-05-21 22:30:09 +00:00
return organizations
end
2012-04-10 14:06:46 +00:00
end