views:

121

answers:

1

So in another controller, I use a find like this:

@entries = Entry.find(:all, :conditions => ['live = ?', false])

to find all the entries with a false 'live' column.

In my project I'm using two different taggable types, one for entries (Entry), and one for messages (Message). After looking at my tried and true code above you would think that I could do something similar to find all the tagged messages with the "Message" value in the taggable_type column of the taggings table.

#this could help find only Messages with the taggable_type column value "Message"
@tagged_messages = Message.find(:all, :conditions => ['taggable_type = Message', true])

The problem here is that my find condition addresses the Message model [Message.find(...] Which won't work because [from my understanding] the taggings table doesn't have an associated model. I'm probably wrong. So how do I search a table that's not associated with a model? I'm probably completely missing something here. I would greatly appreciate any help or code that would help me understand this or help get this working. Thanks for reading my question.

+1  A: 

@tagged_messages = Tagging.find_all_by_taggable_type('Message').map(&:taggable) should do what you want. You might need to throw a uniq in there somewhere as well.

x1a4
Thank you very much. I was unaware of .map()
Take a look at the Enumerable module. It has several interesting things like `map`. The array class holds some fun things that can make life easier as well.Also, if you know the name of a class that you need to make calls on, but it's a string, you can turn it into the real class with `constantize` in Rails, or `Kernel.const_get` in straight Ruby.e.g. `foo = "Message"; foo.constantize.find(1)`
x1a4