On Thu, Jan 15, 2009 at 04:54, sohdubom <[email protected]> wrote: > > Hi, suppose I have the classic Post, Categorization and Category > models example, normalized via join model Categorization in a > has_many_through relationship. If I do: > > 1. pst1 = Post.find(:all, :conditions => "title like 'ibovespa%'") > then pst1 will be an array, because find(:all...) returns an array, > although in this case it's an array of only 1 object
Yes, it's an array, but there is no guarantee that it will always contain only one object. The number of results is dependent on your data, not on your code. If you want to use the objects in the array to traverse their relationships, you should iterate over the array. You should not attempt to use a "title like X" query to retrieve a single post, that is unreliable. If the title is a valid alternate key and you have made sure you have a unique constraint in your database, you can use this to get the object with a specific title: Post.find_by_title(title).first which will return nil if there is no post with the given title. Max > > 2. pst2 = Post.find(1) > then pst2 will be a single object > > In order to find which categories a single post belongs to I could > think of doing: > > cats = pst2.categories and pst1.categories will no work because it's > an array, right? > > Is there a way to still use pst1 to find its categories? > > > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby or Rails Oceania" 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/rails-oceania?hl=en -~----------~----~----~----~------~----~------~--~---
