Finding items from two models - then merging them


#1

I have a model, listings. Listings habtm categories and subcategories,
which are seperate models.

What I want to do is search categories for certain items, like so:

@categories = Category.find(:all, :conditions => [“name LIKE ?”,
“#%{:search_string}%”

and subcategories for the same:

@subcategories = Subcategory.find(:all, :conditions => [“name LIKE ?”,
“#%{:search_string}%”

Then I want to get @categories.listings, @subcategories.listings, merge
them into @listings, sort them by once of their fields, and display
them like so:

<% for listing in @listings %>
<%= render :partial action => “listing” %>
<% end %>

Any ideas? I know how to sort one of the find results, but merging them
doesn’t seem so simple.

Thanks,

Adam


#2

That does not sound like the best way to model categories and sub
categories, which are basically the same thing. A category has many
subcategories, a subcategory has one parentCategory. acts_as_nested_set
might help you as well.
http://api.rubyonrails.com/classes/ActiveRecord/Acts/NestedSet/ClassMethods.html


#3

Shane S. wrote:

That does not sound like the best way to model categories and sub
categories, which are basically the same thing. A category has many
subcategories, a subcategory has one parentCategory. acts_as_nested_set
might help you as well.
http://api.rubyonrails.com/classes/ActiveRecord/Acts/NestedSet/ClassMethods.html

You’re probably right. I used the current method because this is my
first Rails app and I wanted to use what I knew (which was habtm). :slight_smile:

(Can I make the declaration with class Subcategory < Category? How will
that work with Subcategory inheriting has_many :subcategories?)

My question actually still holds, but for a different reason. :slight_smile: I can
now get all categories and all subcategories into one array. But now I
need to also:

find listings using the same search input, but checking different fields
(i.e. listing.agency)
merge those listings with an array of listings gotten by going over
categories and subcategories
eliminate duplicates

Just thinking about it I’m assuming I’m going to need some large,
complicated procedure to do it all. But if there’s any easier way I’d
like to learn beforehand. >_>

Thanks,

Adam