memberships_performance.diff

v2 - no reason to use preload for one entity - Ondřej Ezr, 2016-08-12 17:15

Download (3.13 KB)

View differences:

app/controllers/users_controller.rb
68 68
    end
69 69

  
70 70
    # show projects based on current user visibility
71
    @memberships = @user.memberships.where(Project.visible_condition(User.current)).to_a
71
    @memberships = @user.memberships.preload(:roles, :project).where(Project.visible_condition(User.current)).to_a
72 72

  
73 73
    respond_to do |format|
74 74
      format.html {
app/models/principal.rb
28 28

  
29 29
  has_many :members, :foreign_key => 'user_id', :dependent => :destroy
30 30
  has_many :memberships,
31
           lambda {preload(:project, :roles).
32
                   joins(:project).
31
           lambda {joins(:project).
33 32
                   where("#{Project.table_name}.status<>#{Project::STATUS_ARCHIVED}")},
34 33
           :class_name => 'Member',
35 34
           :foreign_key => 'user_id'
app/models/user.rb
544 544
    @membership_by_project_id[project_id]
545 545
  end
546 546

  
547
  def roles
548
    @roles ||= Role.joins(members: :project).where(["#{Project.table_name}.status <> ?", Project::STATUS_ARCHIVED]).where(Member.arel_table[:user_id].eq(id)).uniq
549
  end
550

  
547 551
  # Returns the user's bult-in role
548 552
  def builtin_role
549 553
    @builtin_role ||= Role.non_member
......
584 588
        end
585 589
      end
586 590
    end
587
    
591

  
588 592
    hash.each do |role, projects|
589 593
      projects.uniq!
590 594
    end
......
653 657
      return true if admin?
654 658

  
655 659
      # authorize if user has at least one role that has this permission
656
      roles = memberships.collect {|m| m.roles}.flatten.uniq
657
      roles << (self.logged? ? Role.non_member : Role.anonymous)
658
      roles.any? {|role|
660
      rls = roles.to_a
661
      rls << builtin_role
662
      rls.any? {|role|
659 663
        role.allowed_to?(action) &&
660 664
        (block_given? ? yield(role, self) : true)
661 665
      }
app/views/groups/show.api.rsb
12 12
  end if include_in_api_response?('users') && !@group.builtin?
13 13

  
14 14
  api.array :memberships do
15
    @group.memberships.each do |membership|
15
    @group.memberships.preload(:roles, :project).each do |membership|
16 16
      api.membership do
17 17
        api.id membership.id
18 18
        api.project :id => membership.project.id, :name => membership.project.name
......
22 22
              attrs = {:id => member_role.role.id, :name => member_role.role.name}
23 23
              attrs.merge!(:inherited => true) if member_role.inherited_from.present?
24 24
              api.role attrs
25
            end 
25
            end
26 26
          end
27 27
        end
28 28
      end if membership.project