1

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.

Dan Tappin
  • 2,692
  • 3
  • 37
  • 77
  • Possible duplicate of [Ransack: How to use existing scope?](http://stackoverflow.com/questions/12949915/ransack-how-to-use-existing-scope) – Brad Werth Nov 26 '15 at 06:21
  • or maybe http://stackoverflow.com/questions/15849054/how-to-filter-results-with-ransack – Brad Werth Nov 26 '15 at 06:22
  • Hmmm... I was close. I have a boolean in my Enrollment table. If I search for the true records it works and if I search for the false records it works but I get the results repeated. – Dan Tappin Nov 26 '15 at 09:19
  • Ok... I guess you have to add result(distinct: true) to filter out the duplicates – Dan Tappin Nov 26 '15 at 09:35

1 Answers1

0

I forgot I had asked this already and I have answered it over here:

Scoping an association search with Ransack

Community
  • 1
  • 1
Dan Tappin
  • 2,692
  • 3
  • 37
  • 77