Search code examples
ruby-on-railsruby-on-rails-4database-designdatabase-schemamodel-associations

Rails: how to get records based on user interests from my current associations?


I have this relationship:

class Trip < ActiveRecord::Base
  belongs_to :user
  acts_as_taggable
  acts_as_taggable_on :activities
end

class User < ActiveRecord::Base
  has_many :trips
  has_many :user_interests
  has_many :interests, through: :user_interests
end

class Interest < ActiveRecord::Base
  has_many :user_interests
  has_many :users, through: :user_interests
end

Users are able to select certain types of interests, and these Trips have activities tagged with them. I want to be able to get records of the Trips that has certain activities that the user are interested.

I've been testing some things out like this:

= Trip.all.to_json (sees all the Trip records) and = current_user.interests.to_son (sees what current user interested in) just to test if it works... and it does.

Is it possible to get only the trips that the users are interested in?


Solution

  • I assume Interest model has name attribute and now question is to find all trips to which user is interested for.

    As you are using acts_as_taggable on gem, you can do something like -

    Trip.tagged_with(user.interests.pluck(:name), on: :activities, any: true)