在users_controller的每个方法中添加User.where(organisation_id: current_user.organisation_id)的目的是为了筛选出与当前用户所属组织相关的用户数据。如果你想要避免在每个方法中重复添加这段代码,可以考虑以下替代的解决方案:
class UsersController < ApplicationController
before_action :filter_users_by_organisation
def index
# ...
end
def show
# ...
end
# ...
private
def filter_users_by_organisation
@users = User.where(organisation_id: current_user.organisation_id)
end
end
class User < ApplicationRecord
belongs_to :organisation
# ...
end
class Organisation < ApplicationRecord
has_many :users
# ...
end
然后,在控制器中可以直接通过current_user.organisation.users来获取相关的用户数据。
class User < ApplicationRecord
scope :by_organisation, ->(organisation_id) { where(organisation_id: organisation_id) }
# ...
end
然后,在控制器中可以通过User.by_organisation(current_user.organisation_id)来获取相关的用户数据。
这些替代方案可以根据具体情况选择使用,以提高代码的可维护性和重用性。
领取专属 10元无门槛券
手把手带您无忧上云