Search code examples
sqlruby-on-railsactiverecordactive-record-query

Rails ActiveRecord query where relationship does not exist based on third attribute


I have an Adventure model, which is a join table between a Destination and a User (and has additional attributes such as zipcode and time_limit). I want to create a query that will return me all the Destinations where an Adventure between that Destination and the User currently trying to create an Adventure does not exist.

The way the app works when a User clicks to start a new Adventure it will create that Adventure with the user_id being that User's id and then runs a method to provide a random Destination, ex:

Adventure.create(user_id: current_user.id) (it is actually doing current_user.adventures.new ) but same thing

I have tried a few things from writing raw SQL queries to using .joins. Here are a few examples:

Destination.joins(:adventures).where.not('adventures.user_id != ?'), user.id)

Destination.joins('LEFT OUTER JOIN adventure ON destination.id = adventure.destination_id').where('adventure.user_id != ?', user.id)


Solution

  • The below should return all destinations that user has not yet visited in any of his adventures:

    destinations = Destination.where('id NOT IN (SELECT destination_id FROM adventures WHERE user_id = ?)', user.id)
    

    To select a random one append one of:

    .all.sample
    # or
    .pluck(:id).sample
    

    Depending on whether you want a full record or just id.