0

I'm using Devise and Rolify.

Employee belongs_to User and User has_one :employee. The User model has rolify.

Because of Rolify, there is a table called user_roles.

The following code works fine:

<% if current_user.has_role? :super %>

And this would work if I wanted to associate with the user instead of the employee:

:collection => User.with_role(:agent)

Now, I would like to have an association in a form that contains a select for employees that have a role of "agent".

The following tries don't work:

<%= f.association :employee, :collection => Employee.user.with_role(:agent), :label_method => :employee_full_name, :label => 'Agent' %>

The one above gives this error:

undefined method `user' for #<Class:0x007fac48215ee8>

This doesn't work either:

<%= f.association :employee, :collection => User.with_role(:agent).employee.id, :label_method => :employee_full_name, :label => 'Agent' %>

What would work?

Thanks for the help!

UPDATE1

The following works to display a list of employees with their associated role:

<td><%= employee.user.roles.first.name %></td>

UPDATE2

Because employee.user.roles.first.name will give me the role name for an employee, I tried this:

Employee.where('employee.user.roles.first.name = ?', 'agent')

But, I get a PG error =

PG::Error: ERROR:  improper qualified name (too many dotted names): employee.user.roles.first.name
4

3 回答 3

1

Employee.user.with_role(:agent)

带回所有具有代理角色的员工。您的前 2 个问题是您正在调用has_role尚未Employee被“rolified”的。

于 2013-07-11T20:43:18.620 回答
0

就这样吧。

Employee.joins(:user).where(:employees => { :user_id => User.with_role(:agent) })

于 2013-08-25T23:08:34.277 回答
0

您正在尝试将实例方法“用户”调用到 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))
于 2013-08-21T20:40:13.010 回答