overriding find

118 views
Skip to first unread message

Will

unread,
Mar 28, 2008, 9:26:19 PM3/28/08
to Ruby on Rails: Talk
Hi,

I am using single table inheritance which looks something like this:

class Employee < ActiveRecord::Base
belongs_to :employee_type
end
Manager < Employee
Programmer < Employee

When I call Manager.find(...) or Programmer.find(...) regardless of
what parameters are passed to find I only want that employee type to
be returned. So Prgrammers.find(:all) will return all programmers, but
not managers.

I somehow need to inject a condition "member_type = xxx" into every
find query of the Employee subclass.

I would like to be able to do it without any restrictions on calling
find. So find(:first), find(id) and find(:all) will all work.

Has anyone done this before or can point me in the right direction?

Regards

Will

Phlip

unread,
Mar 28, 2008, 9:34:26 PM3/28/08
to rubyonra...@googlegroups.com
Will wrote:

> I am using single table inheritance which looks something like this:
>
> class Employee < ActiveRecord::Base
> belongs_to :employee_type
> end
> Manager < Employee
> Programmer < Employee
>
> When I call Manager.find(...) or Programmer.find(...) regardless of
> what parameters are passed to find I only want that employee type to
> be returned. So Prgrammers.find(:all) will return all programmers, but
> not managers.

Google [rails polymorphic association]!

--
Phlip

Kyle

unread,
Mar 29, 2008, 12:34:51 PM3/29/08
to Ruby on Rails: Talk
Will,

It looks like STI is what you're using and what you want (assuming
your data lives in one table). Looking at the AWDwRoR book, it
doesn't seem like you need the belongs_to :employee_type in your
Employee class unless it's related to something else in your app.
Also, I'm assuming that you have abbreviated your Manager and
Programmer classes and that they actually look like this:

class Manager < Employee
end

class Programmer < Employee
end

What does the data in your employees table look like? Do you have a
"type" column that stores either "Manager" or "Programmer" in it? I
haven't used STI before, but based on the examples that I've seen, it
should work as you want it to as long as it's set up correctly.

-Kyle

Danimal

unread,
Mar 29, 2008, 1:48:54 PM3/29/08
to Ruby on Rails: Talk
What Kyle said. :-)

create_table :employees do |t|
t.string :type, :default => "Employee", :null => false
t.string :name
(... other fields ...)
end

Then all you need is the model extensions like Kyle wrote:

class Employee < ActiveRecord::Base; end
class Manager < Employee; end
class Programmer < Employee; end

And you can do stuff like:

managers = Manager.find :all
best_programmers = Programmer.find_all_by_language("Ruby on Rails")
all_employees = Employee.find :all

-Danimal

Will

unread,
Mar 30, 2008, 3:10:40 AM3/30/08
to Ruby on Rails: Talk
Thanks all for your replies. The type field will sort this out.
Reply all
Reply to author
Forward
0 new messages