【问题标题】:dynamically set named_scope based on current_user根据 current_user 动态设置 named_scope
【发布时间】:2011-01-09 17:51:23
【问题描述】:

我不断收到以下错误:

当你没有时你有一个 nil 对象 期待它!你可能已经预料到了 数组的实例。发生错误 在评估 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

用户模型 属于_to :contact

联系方式 has_one:用户 belongs_to :contactable, :polymorphic => true, :dependent => :destroy

网站模型 has_many :contacts, :as => :contactable has_many :学生

学生模型 归属地:站点

这成功地按站点限制了学生: 学生控制器 def index_scoper 如果 current_user.role_id == 8 super.site_staff_limit 别的 super.with_state.with_site 结尾 结束

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

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

【问题讨论】:

  • 你有没有机会更好地格式化你的代码?谢谢。

标签: ruby-on-rails dynamic model controller named-scope


【解决方案1】:

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

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

【讨论】:

  • 我已经尝试了几十种解决方案,包括许多不同的错误。例如,我尝试创建三个 named_scopes,然后在控制器中引用它们: super.current_user(:contact_id).contacts(:contactable_id, :contactable_type).site_staff_limit(:site_id) 但这给出了无关联错误。
  • 等一下……您似乎正在尝试使用“super”调用控制器上的范围?
  • yes super 包含学生信息。它继承自在 lib 目录中创建的 restfulcontroller 中的一个方法,students 控制器从该目录继承。所以 super 指的是学生模型。
  • 那么你的模型是从控制器继承的?
  • StudentsController 继承了 Restful Controller 的关键字 super。然后我将 named_scope 应用到 super 以限制结果。 Super 包含所有记录。我想通过 current_user 的 site_id 来限制。
猜你喜欢
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多