1
\$\begingroup\$
  def current_active_role
    user_roles.each do |r|
      if r.is_active_role
        return r
      end
    end
    return nil
  end

The block above returns whatever the user's currently active role is. There are User, UserRoles (lookup table), and Roles tables.

I'm looking for a more concise way to say "go through all their individual roles, find the active one and return it, or implicitly return nil if none of them are the active role."

\$\endgroup\$
2
\$\begingroup\$

You never want to combine select with a first. Instead, use detect.

def current_active_role
  user_roles.detect(&:is_active_role)
end
\$\endgroup\$
  • \$\begingroup\$ Oh, my, I mixed abstractions in my answer. of course this is the way... \$\endgroup\$ – tokland Jan 16 '15 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.