How can we express this using activerecord?

I have a Profile model that has a given gender and a list of genders they’d be attracted to:

class Profile < ApplicationRecord
  belongs_to :gender, required: false
  has_and_belongs_to_many :genders
end

The HABTM association lists the genders a profile is attracted to and the belongs_to lists the gender a profile identifies as.

class Gender < ApplicationRecord
end

I’m trying to pull out for a given profile all the profiles that are of the genders that profile is attracted to but also ensure that these profiles are also attracted to the gender of the given profile.

I’m wracking my brain and unable to find a way to make this work. Anyone have any insight on how to make it work?

2 Likes

You may want to have a join model in here, rather than the “dumb” HABTM join model. What you’re describing is similar to a “directional join”, where you need to decorate that middle key to indicate some quality that describes that join.

If you’ve done the Hartl Rails tutorial, this is covered under the notions of follows and following in the Fake Twitter that you build there.

Walter

1 Like

I ended up going with an association model called Attraction.

The query ended up being really easy too but I had to learn about merge to make it happen.

Profile.where.not(profiles: { id: profile.id })
  .where(gender_id: profile.attractions.map { |a| a.gender_id }.to_a )
  .merge(
    Profile.joins(:attractions).where(
      attractions: { gender_id: profile.gender_id }
    )
)

Thanks for the recommendation to use an association model.

2 Likes

Hi, From Rails 7 on, you can use the “excluding” method to exclude the current profile Cheers