Rails: 如何从我当前的关联中获取基于用户兴趣的记录?

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

我有这样的关系:

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

用户能够select 某些类型的兴趣,并且这些旅行有标记有它们的活动。我希望能够获取具有用户感兴趣的某些活动的旅行记录。

我一直在像这样测试一些东西:

= Trip.all.to_json(查看所有旅行记录)和 = current_user.interests.to_son(查看当前用户感兴趣的内容)只是为了测试它是否有效……确实如此。

是否可以只获取用户感兴趣的行程?

这个查询怎么样:

Trip.includes('user_interests').where('trip.user_id = user_interests.user_id').references(:user_interests)

这将为您提供用户感兴趣的所有行程。

所以您想查找 trip->activities 匹配 user->interests 的行程? 假设您的兴趣模型具有 name 属性,则以下工作:

Trip.includes(taggings: :tag).where(tags: {name: current_user.interests.pluck(:name)})

我会建议您将此作为方法封装在您的用户模型中,如下所示:

class User > ActiveRecord::Base
  #..
  #..

  def trips_interested_in
    Trip.includes(taggings: :tag).where(tags: {name: self.interests.pluck(:name)})
  end
end

这样你就可以打电话:

trips = @user.trips_interested_in

And/Or 您还可以将其添加为 Trip 模型中的范围,如下所示:

class Trip > ActiveRecord::Base
  scope :where_user_is_interested_in, ->(user) { includes(taggings: :tag).where(tags: {name: user.interests.pluck(:name)}) }

  #..
  #..
end

所以你也可以调用:

trips = Trip.where_user_is_interested_in(@user)

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

当您使用 acts_as_taggable on gem 时,您可以执行类似 -

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