Hi!
I have a little problem with two specially related models and an
accesor for one of them.
In our application, we have users (with a rights/roles subsystem) and
documents. For each document, we have some users related to it, each
one playing one role in that document. Some of them:
class Document < ActiveRecord::Base
belongs_to :adviser, :class_name => ‘User’, :foreign_key => ‘adviser_id’
belongs_to :owner, :class_name => ‘User’, :foreign_key => ‘owner_id’
end
Documents are related to users this way, but users are related to
documents thinking that a user has a document if he participe in some
of the posible roles (adviser, owner…). But some special users have
access to more documents that those ones (for example, they can have
access to all documents created and associated on his office, that
it’s another attribute of both the document and the user models). So,
instead of use has_many :documents on User model, we created the
following method on the User model:
class User < ActiveRecord::Base
def documents
if self.can(‘view all documents’)
Document.find :all
elsif self.can(‘view all office documents’)
Document.find :all, :conditions => { :office_id => self.office_id
}
else # show only documents with direct user participation
Document.find :all, :conditions => “(adviser_id = #{self.id} or
owner_id = #{self.id})”
end
end
end
This works very well, but now we have a little problem. We want to use
the User::documents method by adding some additional conditions or
other find parameters, because we use customizable pagination, and a
selector to allow the users to filter the documents. Something like:
current_user.documents :conditions => ‘status = 3’, :limit => 20
We first tried to use with_scope:
def documents(options = {})
with_scope :find => options do
if self.can(‘view all documents’)
Document.find :all
elsif self.can(‘view all office documents’)
Document.find :all, :conditions => { :office_id => self.office_id
}
else # show only documents with direct user participation
Document.find :all, :conditions => “(adviser_id = #{self.id} or
owner_id = #{self.id})”
end
end
end
But didn’t work. Of course, we can create a method with all the
possibilities as parameters, and merge the conditions, but that is
boring (and doesn’t look well).
Is there any other “Ruby-way” alternative?
Thanks!