【发布时间】: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