Is there a way to define "sub models" in Rails?

Hi there !

Consider the following 2 initial models:

My question:

Is there a way in Rails to define some sort of a "sub model", like
this? (And if yes, how exactly?)

project: -------- has_many :tasks has_many :unfinished_tasks, :class => 'task', :conditions => { :unfinished => true }

Apart from the fact that the option for specifying the class name
is :class_name and not :class, what you've got there should already
work.

Fred

Oh, very cool, thanks Fred!

Consider the following 2 initial models:

project: -------- has_many :tasks

[...]

My question:

Is there a way in Rails to define some sort of a "sub model", like this? (And if yes, how exactly?)

project: -------- has_many :tasks has_many :unfinished_tasks, :class => 'task', :conditions => { :unfinished => true }

[...]

I generally like to define methods on the has_many collection for that sort of thing:

has_many :tasks do   def unfinished     select(&:unfinished?)   end end

This allows you to call @project.tasks.unfinished to get the collection of unfinished tasks. That said, if you are trying to avoid retrieving or instantiating the finished tasks, use the other approach with the conditions clause. This approach requires loading (or having loaded) the entire tasks collection.

Thanks for any help with this! Tom

--Greg

It should be :class_name => “Task” and not :class_name => “task”. If you left it lower case you’d get Rails whinging that it can’t find a local variable called “task”, which can lead to a lot of wtf’ing before figuring that out.