Overriding the has_many accessor

Shop: has_many :workers
Worker: belongs_to :shop

s = Shop.find(:first)

Calling s.workers.create(…) works great. The problem is, I want
s.workers to only return CURRENT workers.

:conditions => { :current => true }

Here’s my attempt at fixing it:

alias all_workers workers
def workers
all_workers.find(:conditions => { :current => true })
end

This causes s.workers to correctly return only current workers. The
problem is, s.workers.create is now broken (“can’t call ‘create’ on an
array”). Also, s.workers_count will be wrong.

Is there any way to override Shop#workers so that it returns the correct
information everywhere?

Thanks,

- Scott

Scott B. wrote:

Shop: has_many :workers
Worker: belongs_to :shop

s = Shop.find(:first)

Calling s.workers.create(…) works great. The problem is, I want
s.workers to only return CURRENT workers.

:conditions => { :current => true }

class Shop < AR::B
has_many :all_workers
has_many :workers, :conditions => ‘workers.current = true’
end


We develop, watch us RoR, in numbers too big to ignore.

Mark Reginald J. <mrj@…> writes:

:conditions => { :current => true }

class Shop < AR::B
has_many :all_workers
has_many :workers, :conditions => ‘workers.current = true’
end

How about this:

class Shop < AR::B
has_many :workers do
def current
find(:all, :conditions => ‘workers.current = true’)
end
end
end

This gives you @shop.workers and @shop.workers.current

Gareth