From c53798bfcfb184a43320f75b14fa430c8e1fe613 Mon Sep 17 00:00:00 2001 From: Romano Licker Date: Wed, 18 Jul 2012 10:14:40 +0200 Subject: [PATCH] refactor possible_members * projects makes more sense when speaking of "possible_members" * using named scopes results in one single query for the database --- app/models/principal.rb | 8 +++----- app/models/project.rb | 4 ++++ app/views/projects/settings/_members.rhtml | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/app/models/principal.rb b/app/models/principal.rb index dc7dbdc778..3356712456 100644 --- a/app/models/principal.rb +++ b/app/models/principal.rb @@ -23,7 +23,9 @@ class Principal < ActiveRecord::Base named_scope :active, :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status = 1)" named_scope :active_or_registered, :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND (#{Principal.table_name}.status = 1 OR #{Principal.table_name}.status = 2))" - + + named_scope :not_in_project, lambda { |project| {:conditions => "id NOT IN (select u.id from users as u, members as m, member_roles as r where m.id = r.member_id AND m.project_id = #{project.id} AND m.user_id = u.id)"}} + named_scope :like, lambda {|q| s = "%#{q.to_s.strip.downcase}%" {:conditions => ["LOWER(login) LIKE :s OR LOWER(firstname) LIKE :s OR LOWER(lastname) LIKE :s OR LOWER(mail) LIKE :s", {:s => s}], @@ -37,10 +39,6 @@ class Principal < ActiveRecord::Base to_s end - def self.possible_members(criteria, limit) - Principal.active_or_registered.like(criteria).find(:all, :limit => limit) - end - def <=>(principal) if self.class.name == principal.class.name self.to_s.downcase <=> principal.to_s.downcase diff --git a/app/models/project.rb b/app/models/project.rb index 916d59ab4f..3c79461922 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -109,6 +109,10 @@ class Project < ActiveRecord::Base errors[:identifier].nil? && !(new_record? || identifier.blank?) end + def possible_members(criteria, limit) + Principal.active_or_registered.like(criteria).not_in_project(self).find(:all, :limit => limit) + end + # returns latest created projects # non public projects will be returned only if user is a member of those def self.latest(user=nil, count=5) diff --git a/app/views/projects/settings/_members.rhtml b/app/views/projects/settings/_members.rhtml index 6a146b0ec6..74d05b4e6b 100644 --- a/app/views/projects/settings/_members.rhtml +++ b/app/views/projects/settings/_members.rhtml @@ -1,7 +1,7 @@ <%= error_messages_for 'member' %> <% roles = Role.find_all_givable - available_principals = Principal.possible_members("", 100) - @project.principals %> members = @project.member_principals.find(:all, :include => [:roles, :principal, :member_roles]) + available_principals = @project.possible_members("", 100) %>
<% if members.any? %>