Simple_form f.association对模型关联的子集

时间:2014-05-01 13:37:40

标签: ruby-on-rails simple-form rolify

我有一个代理商,has_many :users。用户可以拥有角色 - :agent,:admin,因此我创建了拉动@ agency.users

子集的方法
Agency.rb
def agents
  users.with_roles(:agent, self)
end

我想要的是,f.association :agents, collection: User.all允许代理商雇用任何人。不出所料,尝试这一点会给“协会:未找到代理人”。将其更改为f.association @agency.agents, collection: User.all也会因"Association #<ActiveRecord::AssociationRelation .....not found"

而失败

this question开始,似乎simpleform无法处理AssociationRelation,但只能处理一个Association。

我可以改变我的方法只返回一个关联吗?我可以改变我的simpleform来处理AssociationRelation吗?

1 个答案:

答案 0 :(得分:2)

所以,解决方案结果有点像hacky,但似乎有效:

需要它是一个关联,而不是方法,但事实证明我可以确定我的关联范围。

Agency.rb
has_many :bridge_roles, -> {where(resource_type: 'Agency')}, class_name: 'Role', foreign_key: :resource_id
has_many :agents, -> {where('roles.name=?', 'agent')}, class_name: 'User', through: :bridge_roles, source: :users

关键是我明确地创建了桥,以使关联知道rolify角色。通过它,我可以访问我关心的用户组。