goddamnyouryan
goddamnyouryan

Reputation: 6906

Rails 3 App, "following" different types of models

I am building a rails 3 App. I'll try to describe this application to the best of my ability and as succinctly as possible.

The two main types of models in this app are:

Then there are two other models:

How they work together is: the Businesses can have (or belong to, rather) as many categories as they like (and any related subcategories as well).

The user can chose categories to "follow", i.e. they select the categories that they want to show up in their feed, and any businesses that belong to these categories will show up in the feed (same with subcategories)

It's important to note that the categories and subcategories will be dictated by the admins only, the users/businesses can't add/destroy categories, only follow existing ones

My plan for how to implement this was to create a "Following" model with the following attributes

of which there would be two "followable_types": user, and business. As you can see this is a not-quite polymorphic model.

Where I am running into trouble is the methods. For example, how would I create a list of all the businesses that belong to the categories the user is following? It would require some tricky queries and a lot of hackery. This leads me to believe I am approaching the problem from the wrong angle.

Could someone steer me in the right direction? Maybe my architecture needs some work. Or give me a hint as to how I should be writing my methods.

Thanks!!

Upvotes: 2

Views: 593

Answers (1)

Ant
Ant

Reputation: 3887

Given the queries you'll be regularly performing I would probably do away with the polymorphism in this case and do something like:

class Customer < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

class Business < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

class Categories < ActiveRecord::Base
  has_and_belongs_to_many :customers
  has_and_belongs_to_many :businesses
end

Then the code to perform the query you suggested is pretty simple:

Business.joins(:categories).where('categories.id IN (?)', a_user.categories.map(&:id))

Upvotes: 3

Related Questions