[英]Rails Devise Rolify collection of employee with a role
我正在使用Devise和Rolify。
员工belongs_to User
,用户has_one :employee
。 用户模型已rolify
。
由于存在Rolify,因此存在一个名为user_roles
的表。
以下代码可以正常工作:
<% if current_user.has_role? :super %>
如果我想与用户而不是与员工关联,这将起作用:
:collection => User.with_role(:agent)
现在,我想以一种形式包含一个关联,该关联包含对具有“代理”角色的员工的选择。
以下尝试不起作用:
<%= f.association :employee, :collection => Employee.user.with_role(:agent), :label_method => :employee_full_name, :label => 'Agent' %>
上面的一个给出了这个错误:
undefined method `user' for #<Class:0x007fac48215ee8>
这也不起作用:
<%= f.association :employee, :collection => User.with_role(:agent).employee.id, :label_method => :employee_full_name, :label => 'Agent' %>
什么会起作用?
谢谢您的帮助!
更新1
以下工作显示具有相关角色的员工列表:
<td><%= employee.user.roles.first.name %></td>
更新2
因为employee.user.roles.first.name
将给我一个雇员的角色名称,所以我尝试了以下操作:
Employee.where('employee.user.roles.first.name = ?', 'agent')
但是,我收到PG错误=
PG::Error: ERROR: improper qualified name (too many dotted names): employee.user.roles.first.name
Employee.user.with_role(:agent)
带回所有具有代理角色的员工。 前2个问题是您正在对尚未被“ rolized”的Employee
调用has_role
。
您试图将实例方法“ user”调用到Employee类。 如您所说,如果Employee属于用户,那么您将希望在那里加入(我假设您在User模型中具有has_one:employee关系):
Employee.joins(:user => :user_roles).merge(User.with_role(:agent))
要么
Employee.joins(:user => { :user_roles => :roles}).merge(User.with_role(:agent))
来了
Employee.joins(:user).where(:employees => {:user_id => User.with_role(:agent)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.