Browse the Ruby on Rails Community.

You are here: Forums Ask a Rails expert Optimising code...

Replytotopic

Optimising code

Posted in Forums : Ask a Rails expert

 
N625997419_7752

Authority 25
Posting Rating 60
Sign in to rate this post

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

 
Profile

Authority 25
Posting Rating 21
Sign in to rate this post

Use following association in your model building-

has_many :roles, :incldue=>:user, :conditions=>”user.role_type = ‘Admin’ “

 
Me_on_a_train

Authority 87
Posting Rating 84
Sign in to rate this post

Here’s my refactoring: gist.github.com/136835

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

 
N625997419_7752

Authority 25
Posting Rating 60
Sign in to rate this post

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

Nicolas

Replytotopic

Other Recent Topics

Ask a Rails expert : nested application ApplicationController get called intead of children::ApplicationController

Ask a Rails expert : Best way to structure a database for a large/static dataset

Ask a Rails expert : Ruby Developer (ROR) - Scottish based (Remote working from within the UK)

Ask a Rails expert : Above Ground Pool Supplies

Ask a Rails expert : How to get url params in observer or model in Rails 3.1

Ask a Rails expert : What can persuade you to hire Junior Ruby devs with significant PHP experience?

Ask a Rails expert : What industry value does the Ruby or Rails Certification currently have?

Ask a Rails expert : Louis Vuitton Damier Azur Canvas specially sale ( www.salecheaplouisvuitton.com )

Ask a Rails expert : ·How to check errors/puts statements from ruby files which are under cronob

Ask a Rails expert : Louis Vuitton cheap Soft Sided Luggagespecial offer( www.salecheaplouisvuitton.com )

Formatting Help
  • *bold*       _italics_      
    bq. (quotes)
  • "DSC":http://www.dsc.net
  • * or # (lists)
or cancel