你会如何重构这个?

时间:2013-02-28 02:02:00

标签: ruby-on-rails refactoring

'def show

 @dept = Dept.find(params[:id])
    @members = @dept.members_list.collect{|a|a.name}
    dif = @dept.users.collect{|a|[a.name,a.id]}
    @admin_list = @dept.admin_users.collect{|a|a.user}
   @not_member_users = User.all_users - dif
   @not_admin_user = (@dept.list_of_deptmembers - @dept.admin_users).collect{|a|[a.user.name, a.id]}'    

我怎样才能重构@not_admin_user ??

3 个答案:

答案 0 :(得分:1)

在某些情况下搜索基于id的表格会更快,更便宜 - 这可能是其中一种情况。

@dept = Dept.find(params[:id])

# assuming both `members_list` and `admin_users` actually point to `User` objects
member_ids = @dept.members_list.collect(&:id)
admin_ids = @dept.admin_users.collect(&:id)
non_admin_id = member_ids - admin_ids

non_admin_users = User.where("id in ?", non_admin_id)

答案 1 :(得分:0)

对于初学者,您可以将所有逻辑推送到Dept模型中。

def show
  @dept = Dept.find(params[:id])
  @admin_list = @dept.admin_list
  @members = @dept.members
  @not_member_users = @dept.not_member_users
  @not_admin_user = @dept.not_admin_user
end

class Dept < ActiveRecord::Base
  def members
    self.members_list.collect{ |a| a.name }
  end

  def admin_list
    self.admin_users.collect{ |a| a.user }
  end

  def not_member_users(user = User)
    dif = self.users.collect{|a|[a.name,a.id]}
    user.all_users - dif
  end

  def not_admin_user
    (self.list_of_deptmembers - self.admin_users).collect{|a|[a.user.name, a.id]}
  end
end

答案 2 :(得分:0)

最好处理对象集合,而不是对象属性数组。因此@members应该是MemberUser个对象的数组,而不是名称的字符串数组。

这对你的问题可能不是一个很好的答案,但我会遵循从外到底的发展原则,并希望能够得到你想要的东西:

def show
  @dept = Dept.find(params[:id])
  @members          = @dept.members
  @admin_list       = @dept.admin_users
  @not_member_users = @dept.non_member_users
  @not_admin_users  = @dept.non_admin_users
end

在Dept模型中,设置范围/关联,将相应的结果返回到上面使用的方法。使用Ruby过滤结果是最后的手段。