修改 has_many 的行为还是使用范围? [英] Modify the behavior of has_many or use scope?
问题描述
我有一个看起来像这样的类:
I have a class that looks something like this:
class User < ActiveRecord:Base
has_many :users_companies
has_many :companies, :through => :users_companies
end
对于普通用户,我希望 user.companies
引用标准关联方法,但是当用户是管理员时,我希望 User.all
(即,管理员可以访问所有公司).我能想到的最简单的实现方法(以及我过去一直在做的事情)是在 Company 类上使用范围,例如:
For plain users, I'd like user.companies
to refer to the standard association method, but when a user is an admin, I want User.all
(i.e., admins have access to all companies). The simplest way I can think of to implement this (and what I've always done in the past) is use a scope on the Company class, such as:
scope :accessible_by, lambda { |user| ... }
唯一的问题是这感觉不对.而不是编写包含以下内容的控制器操作:
The only problem is that this just doesn't feel right. Instead of writing a controller action that includes:
@companies = Company.accessible_by(current_user)
我觉得写起来更舒服
@companies = current_user.companies
是否有一种好方法可以覆盖 User#companies 方法以适应这种行为?或者,我应该对在公司上使用范围感到满意吗?
Is there a good way to override the User#companies method to accommodate this kind of behavior? Or, should I be happy with using a scope on Company?
推荐答案
我正在努力解决一个类似的问题.我可以设计的唯一可接受的解决方案是 关联扩展,它覆盖管理员用户的查询和通过普通用户的查询,不受干扰.
I'm wrestling with a similar problem. The only acceptable solution I can devise is an association extension, which overrides the query for admin users and passes normal users' queries, unmolested.
# this works for me in rails 3.1
class User < ActiveRecord:Base
has_many :users_companies
has_many :companies, :through => :users_companies do
def visible
if proxy_association.owner.admin?
UsersCompany.scoped
else
self
end
end
end
end
User.where(:admin => true).first.companies.visible == UsersCompany.all
这篇关于修改 has_many 的行为还是使用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!