Hello, my name is Magnus and I am a RoR-newbie. I am trying to get the grip of ActiveRecord but I am having trouble to find good examples. I have been looking at this: http://wiki.rubyonrails.com/rails/show/AccessControlListExample Where you can find this Model code: require ''active_record'' class Permission < ActiveRecord::Base has_and_belongs_to_many :roles end class Role < ActiveRecord::Base has_and_belongs_to_many :permissions has_and_belongs_to_many :users end class User < ActiveRecord::Base has_and_belongs_to_many :roles end As the example says I can use: user = User.find(1) roles = user.roles To get all roles for user with id 1 BUT what if I want to get all the users with all their roles and show them in my view. Is it possible without writing a SQL-statement? I would like to avoid looping all the users and ask for their roles. Br Magnus _______________________________________________ Rails mailing list Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org http://lists.rubyonrails.org/mailman/listinfo/rails
Magnus Hjelm wrote:> I would like to avoid looping all the users and ask for their roles.Then you have to write your own SQL. ActiveRecord doesn''t try to be overly smart - instead it gives you a nice shortcut for 90% of database operations and doesn''t get in the way for the remaining 10%. Ask yourself whether or not this would be a premature optimisation though. -- Best regards, Alexey Verkhovsky Ruby Forum: http://ruby-forum.org (moderator) RForum: http://rforum.andreas-s.net (co-author) Instiki: http://instiki.org (maintainer)
> BUT what if I want to get all the users with all their roles and show > them in my view. Is it possible without writing a SQL-statement? > > I would like to avoid looping all the users and ask for their roles.Personally, I prefer not to bang too hard on the database if I can help it. 1) Implement caching. Caching in Rails is very slick. Though, it only caches the generated HTML. If you''ll be using the user/role data in multiple pages, Tobi''s SimpleCache model (http://typo.leetsoft.com/trac.cgi/file/trunk/app/models/simple_cache.rb) works great if you''re not using CGI. 2) There''s another method that I got from EliteJournal that I explain in a blog posting (http://techno-weenie.net/blog/code/184/rails-best-practices). It would involve selecting all the roles, throwing it into a hash using the user_id as the key, and an array of roles as the value. Then while looping through users, you''d access the roles like: roles[@user.id] I actually implemented this, but went to caching anyway. 3) There''s also the piggy backing method (http://www.loudthinking.com/arc/000235.html), but I don''t think it would work well for many-to-many joins. I use this a lot in my app. -- rick http://techno-weenie.net