The biggest problem with the approach you're using is that it's very 
expensive if your tables get large.  You're iterating over every item 
that exists in the database.  What you want to do is get the database to 
do the filtering for you.

There are several mechanisms in ActiveRecord to help you do that.

First, you can get familiar with find: 
(http://caboo.se/doc/classes/ActiveRecord/Base.html)

class Comment < ActiveRecord::Base
   def user_comments(user)
     find(:all, :conditions => { :user_id => user.id })
   end
end

But that's more low-level than is needed.  In your case, it looks like 
you have

class Comment < ActiveRecord::Base
   belongs_to :user
end

If you add

class User < ActiveRecord::Base
   has_many :comments
end

You can call "user.comments" to get that user's comments.

For more complicated queries, see 
http://cookbook.hobocentral.net/manual/scopes#association_scopes

Or you can use named finders:
http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

cheers,
Bryan


Leonardo Frittelli wrote:
> Fellow "Hoboers",
> 
> I have a doubt about the member_class attribute in collections
> I have noticed that some rapid tags such as  <count> use this method to 
> determine labels that will be displayed alongside their output (e.g: "3 
> Items" for <count:items>)
> 
> Now, say a model BlogPost declares a has_many :blog_comments, then 
> whenever I do a post.blog_comments I will get an Array that will have a 
> "member_class" attribute set to BlogComment. This is somehow done 
> automagically for me by Hobo (I presume).
> 
> The problem is that I now would like to have a new accessor method, that 
> would return all comments posted by a certain user:
> 
> def user_comments(user)
>    blog_comments.collect { |comment|  comment.user == user }.compact
> end
> 
> I have noticed that the magic no longer works for me here, so if I want 
> this collection to work with rapid tags, then I will need to do 
> something like:
> 
> def user_comments(user)
>    coll=blog_comments.collect { |comment|  comment.user == user }.compact
>    coll.member_class = BlogComment
>    coll
> end
> 
> Am I doing anything wrong here? Is there a better way to achieve this end? 
> 
> Thanks!
> 
> Leo
> 
> 
> 
> > 


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Hobo 
Users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/hobousers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to