I have some categories that may contain posts in a has_many relationship. Can I use the "find" method on the object class to only retrieve those categories that are not empty? --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
> Can I use the "find" method on the object class to only retrieve those > categories that are not empty?Category.with_scope(:find => {:conditions => "foreign_key_id != null" } ) may be good for you, but you should dig in a little further to see if this fits your needs; check out with_scope. it will change the find method for the whole class. maybe it''s worth doing something simpler ... -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
My suggestion: class Category has_many :posts end class Post belongs_to :category, :counter_cache => true end In your categories table create a new column "posts_count", not null, default value 0 (or modify your migration similarly). Now every time you make create a post object in a category, that category''s posts_count is increased by one without any intervention from you. Then you can: Category.find(:all, :conditions => ''posts_count > 0'') You can choose to not use this and modify your find statement but each time you use it you will have to sum every category''s posts within the query... I''m actually not even sure what the query would be. I think counter_cache will work out better in the long run. -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---