I've got a model, Agency, which has_many :users
. Users can have roles- :agent, :admin, so I created methods to pull that subset of @agency.users
Agency.rb
def agents
users.with_roles(:agent, self)
end
What I want is, effectively, f.association :agents, collection: User.all
to allow agencies to hire anybody. Trying this gives, unsurprisingly, "Association :agents not found". Changing it to f.association @agency.agents, collection: User.all
also fails with "Association #<ActiveRecord::AssociationRelation .....not found"
From this question, it seems like simpleform can't handle the AssociationRelation, but only an Association.
Can I alter my method to return just an association? Can I alter my simpleform to handle the AssociationRelation?
So, the solution turned out to be a bit hacky, but it seems to work:
I do need it to be an association, rather than methods, but it turned out I could scope my associations.
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
The key being that I created the bridge explicitly to make the association aware of the rolify roles. Through that, I can access the set of Users I care about.