ruby on rails-模型关联子集上的Simple_form f.association



我有一个模型,Agency,它是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" 而失败

从这个问题来看,simpleform似乎无法处理AssociationRelation,而只能处理Association。

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

因此,解决方案有点棘手,但似乎有效:

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

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角色。通过它,我可以访问我关心的用户集。

最新更新