Topic: Shared behaviour and unified searching of similar models

I have been pondering this for a couple of weeks now and I thought it was time I roped in some help. By the way I have another account on RailsForum, I work for one company part time, this a new account for my other stuff!

I have a design for a CMS, each different kind of asset has a model, so we have models for Article, Picture, Song, Product and a few others. Now each of these models has shared behavior, for example the are a number of common fields such as title, description, author_id, published_on, as well associations such as has_one :folder and has_many :tags.

My question is kind of two fold. Firstly I need to work out the best place to put the shared behavior, normally I would use standard Object Inheritance, but the Rails way seems to be the use of a mixin module (ie. acts_as) which is fine. Secondly I need a way to search all the assets at once using the common fields (title, description etc.), my thinking is to have a model call Asset with the common fields plus a field to hold the asset type (eg. Article) and the id of that asset [just like a polymorphic join].

Does this sound like a good plan? smile

Thank me by recommending me on WorkingWithRails

Re: Shared behaviour and unified searching of similar models

chamstar wrote:

but the Rails way seems to be the use of a mixin module (ie. acts_as) which is fine.

Right, mixins are usually the way to go when you need to share behavior between models.

chamstar wrote:

Secondly I need a way to search all the assets at once using the common fields (title, description etc.), my thinking is to have a model call Asset with the common fields plus a field to hold the asset type (eg. Article) and the id of that asset [just like a polymorphic join].

Just to clarify, do you need to search all assets in one big search and have them all turn up in the same result set? In that case, yes, I think making a separate Asset model is the best way to go. This will cause some complications, but it is pretty much the only way to do a search as you need. Alternatively you could do a separate search for each model and add them together, but this gets really messy if you need to sort and limit the results.

Railscasts - Free Ruby on Rails Screencasts

Re: Shared behaviour and unified searching of similar models

A mixin it is then, I found a nice tutorial on writing acts_as (http://revolutiononrails.blogspot.com/s … el/acts_as).

Yeah I need to search all the model and have one resultset. I thought having an Asset model would be best because then only one SQL query is required. I have an after_save hook setup at the moment which save the common fields to the asset table. It seems to work well so far!

It does mean I am saving the same data twice and at some point I might DRY this up, but for now it is good enough.

Cheers Ryan.

Thank me by recommending me on WorkingWithRails