Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible to search nested/polymorphic models? #6

Closed
timnovinger opened this issue Sep 26, 2014 · 3 comments
Closed

Possible to search nested/polymorphic models? #6

timnovinger opened this issue Sep 26, 2014 · 3 comments

Comments

@timnovinger
Copy link

Hi!

I have the following model setup:

class User < ActiveRecord::Base
  belongs_to :meta, polymorphic: true
end

class Client < ActiveRecord::Base
  has_one :user, as: :meta, dependent: :destroy
end

class Coach < ActiveRecord::Base
  has_one :user, as: :meta, dependent: :destroy
end

class Appointment < ActiveRecord::Base
  belongs_to :coach
  belongs_to :client
end

I would like to try to search both clients and coaches by their names and email address, however since these attributes are not on the client or coach model themselves, but are on the polymorphic user model, the following does not work.

search_scope :search do          
  attributes client:   ['client.user.first_name', 'client.user.last_name', 'client.user.email']
  attributes coach:  ['coach.user.first_name', 'coach.user.last_name', 'coach.user.email']
end

I've tried setting up various search scopes and aliases with no luck. Is there a way to do this?

@mrkamel
Copy link
Owner

mrkamel commented Sep 27, 2014

Sure, you have to do the join yourself.

  search_scope :search do
    attributes :user => ["users.first_name", "users.last_name", "users.email"]

    scope do
      joins("left outer join users on (users.meta_id = client_id and meta_type = 'Client') or (users.meta_id = coach_id and meta_type = 'Coach')").group(:id)
    end 
  end 

@mrkamel
Copy link
Owner

mrkamel commented Sep 27, 2014

A more sophisticated example where you can search for them individually and at the same time, would be:

  search_scope :search do
    attributes :client => ["client_user.first_name", "client_user.last_name", "client_user.email"]
    attributes :coach => ["coach_user.first_name", "coach_user.last_name", "coach_user.email"]

    scope do
      joins("left outer join users client_user on (client_user.meta_id = client_id and client_user.meta_type = 'Client') left outer join users coach_user on (coach_user.meta_id = coach_id and coach_user.meta_type = 'Coach')")
    end 

    aliases :client_user => :user, :coach_user => :user
  end 

@timnovinger
Copy link
Author

@mrkamel Thank you so much for your help with this Ben. I used your "sophisticated example" and it worked perfectly. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants