Could I add an association based on another association?

前端 未结 4 552
闹比i
闹比i 2021-01-15 21:41

My User model looks like:

User
   habtm  :Roles


Role
   habtm  :Users


RoleExtension
   belongs_to  :Role

mysql tables:

         


        
相关标签:
4条回答
  • 2021-01-15 22:09
    user = User.find(1)
    RoleExtension.find(:all, :conditions => ["role_id IN (?)", user.role_ids])
    

    Otherwise you can use nested joins.

    0 讨论(0)
  • 2021-01-15 22:27
    @user.role_extensions.where(:joins => :roles)
    
    0 讨论(0)
  • 2021-01-15 22:29

    Normally you'd use a has_many, :through association, but that doesn't apply to has_and_belongs_to_many relations.

    So, instead, in your User model:

    def role_extensions
      return roles.inject([]) do |array, role|
        role.role_extensions do |re|
          array.include?(re) ? array << re : array
        end
      end
    end
    

    Then my_user.role_extensions should return an array of all role extensions belonging to all the user's roles.

    Note: I haven't tested this, but it should work

    UPDATE: I like this better

    def role_extensions
      return roles.inject([]) { |array, role| array << role.role_extensions }.flatten!.uniq
    end
    
    0 讨论(0)
  • 2021-01-15 22:30

    Try this -

    # Fetch user object
    user = User.first
    
    # If you want roles of that user try this
    roles = user.roles
    
    # You can map all the role extensions of that user by
    role_extensions = user.roles.map(&:role_extensions).uniq
    

    Be aware that this will be extremely slow for large number of roles. In that case better write your own query method. Something like

    role_extensions = RoleExtension.where("role_id in (?)", user.role_ids).all
    
    0 讨论(0)
提交回复
热议问题