overriding find

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

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]!

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

What Kyle said. :slight_smile:

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

Thanks all for your replies. The type field will sort this out.