Could I add an association based on another association?

前端 未结 4 556
闹比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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题