I hope I can explain this correctly.
I have the following:
class User < ActiveRecord::Base
has_many :enrollments
has_many :companies, through: :enrollments, dependent: :destroy
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :company
class Company < ActiveRecord::Base
has_many :enrollments
has_many :users, through: :enrollments
These are all in the public tenant in the apartment gem. Company is the tenant. The idea here is that Users are associated to Companies via Enrollments. I have other info in Enrollments so I didn't go with STI.
I can call current_user.enrollments etc. but what I really want is a has_one type association where you get the enrollment from the current tenant.
I added this:
def enrollment
company = Company.where(tenant_name: Apartment::Tenant.current).last
company.enrollments.where(user_id: self.id).last
end
Which works when called but you can't search on it with Ransack etc
For the Ransack a query like enrollments_somefield_eq=somevalue
works fine but it searches all the Enrollments but I want just the enrollments from the current company. I have seen where you can add a condition to the association but I don't think I can get the tenant id in the model to use it.
Any ideas here?
UPDATE
I am close here - after a ton of Googling I cobbled together this:
has_many :active_enrollments, -> { joins(:company).where("companies.tenant_name = '#{Apartment::Tenant.current}'") }, class_name: 'Enrollment'
I really want:
has_one :active_enrollment, -> { joins(:company).where("companies.tenant_name = '#{Apartment::Tenant.current}'").last }, class_name: 'Enrollment'
but this does not work. As there is really only ever one enrollment per company and user. This may be close enough because I can query active_enrollments
via ransack and the scope is applied etc.