I’d like to be able to describe different types of a model using RoR associations. An example:
Models:
Post
ImagePost
post_id:integer
url:string
MessagePost
post_id:integer
message:string
ImagePost and MessagePost are a type of Post. I’d like @posts = Post.all to retrieve both types of post and allow me access to their attributes via @posts.url or @posts.message.
I’m sure I’m missing something simple, please enlighten me!
Cheers,
Ben.
You could try the mixed model approach, but it’s a fair amount of work to set up. It’s bit of of a kludge that trades performance for more efficient database storage.
The idea is that you use STI to handle all the common Post fields, and delegate the unique fields for each subclass to an another table and eager load that association.
The base Post class could look like this. Note the class_eval could be abstracted into a module that gets included and exended into a subclass.
Then you’ll need to define the sub and detail class for each type.
Now we can do things like this:
Which will create a new MessagePost, where the user_id, timestamps, post_id, post_type are all stored in the posts table, while the message is stored in the MessagePostDetails table and return the url of an ImagePost respectively.
The new method_missing and respond_to? definitions work the magic to hide the division.
@Post.allwill now list Posts of all types. The only downside is that the detail fields will not be displayed when you fetch a post.