0

我不断收到以下错误:

当你没想到时,你有一个 nil 对象!您可能期望有一个 Array 的实例。评估 nil.size 时发生错误

根据当前用户,当他们导航到一个页面时,我想将他们限制为他们可以根据他们的网站看到的内容。问题是站点和用户表之间没有直接关联。一个联系人拥有一个用户(用户信息存储在 current_user 变量中)。一个网站有很多联系人。还有一个站点 has_many students,其中学生表的外键为 site_id。因此学生和站点之间存在链接,因此当当前用户导航到学生页面时,他们只能看到与他们来自同一站点的学生。我可以通过在 named_scope 中硬编码一个数字来仅显示 current_user 站点的学生来做到这一点。但是不同的用户将属于不同的站点,因此当登录时,他们关联的站点会发生变化。这就是问题所在 - 在 named_scope 中动态设置该值。这就是我所拥有的:

学生控制器

def index_scoper
  if current_user.role_id == 8
    super.site_staff_limit while current_user[:site_id]
    # The problem is the user table has no site_id. There is no direct
    # link between the users table and sites table. However, there is
    # a link between users and contacts and then site and contacts and
    # then site and students, where students table has site_id.
  else
    super.with_state.with_site
  end
end

学生模型

named_scope :site_staff_limit, lambda {|site_id| {:conditions => {:site_id => site_id}}}

感谢您的任何建议。

表之间的关系:

用户:contact_id 联系人:主键、contactable_id、contactable_type 站点:主键 学生:site_id

用户模型belongs_to :contact

联系模型 has_one :user belongs_to :contactable, :polymorphic => true, :dependent => :destroy

站点模型 has_many :contacts, :as => :contactable has_many :students

学生模型 belongs_to :site

这成功地按站点限制学生: StudentsController def index_scoper if current_user.role_id == 8 super.site_staff_limit else super.with_state.with_site end end

学生模型 named_scope :site_staff_limit, :conditions => {:site_id => 1}

问题是不同的用户将属于不同的站点,因此他们只能访问他们所属站点的学生记录。我很难使以上的 named_scope 足够动态以完成此操作。

4

1 回答 1

1

您也许可以通过 :through 关系在用户和站点之间建立链接。

您提供的代码是否有效?是否发生错误?

于 2010-01-26T23:34:55.557 回答