Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
4 Posts
Optimising code

Hello, I would like some advice on how to optimise my code. I have different model

building has_many roles

role (which brings the type of role for the user for the building) belongs_to building belongs_to user

user has_many roles

And I have a lot of method in the building model to find the different type of member for a building like

def find_admins_of

roles = self.roles

admins = []

for role in roles

  admins << User.find(role.user_id) if role.role_type_id == Role::ADMIN

end

admins

end

This is not the best way to do it but I would like to know which better way. I have thought of a has_many, through but I can't find the right syntax for the conditions on the role.role_type_id

I hope I am clear.

Thanks for your help Nicolas

Use following association in your model building-

has_many :roles, :incldue=>:user, :conditions=>"user.role_type = 'Admin' "

Here's my refactoring: "gist.github.com/136835":http://gist.github.com/136835

I renamed your "role_type_id" attribute to "name", but you can get the idea.

Thnaks very much, I am gonna give it a try. I'll let you know.

Nicolas

4 Posts
Login to add your message