0

我必须使用 Rails 的活动记录或 sql (sqlite) 执行以下查询。

让我们从模型的描述开始。

  • 用户 1:n 兴趣
  • 兴趣 m:n 类别
  • 兴趣 m:n 地点
  • 事件 m:n 类别
  • 活动 m:n 地点

m:n 关系正在通过具有模式interests_categories、events_categories 等的第三个表来实现。

我有用户并且这些用户有兴趣(类别 -> 例如运动、音乐和他喜欢的位置)。事件被标记为位置和类别。

现在我想列出所有可能适合特定事件的用户。例如,如果有一个事件发生在纽约市并且有一些体育活动,我想根据位置和类别获取可能对此事件感兴趣的用户列表。

我想在单个数据库访问而不是多个数据库中进行。在 ActiveRecord 或 sql 中会是什么样子?(更有效的方法是首选)我可能必须先加入类别/位置表,根据先前加入的所有表加入兴趣,然后根据兴趣选择所有用户。不幸的是,我对连接 sql 的了解有限。或者甚至有不同的方法可用?

4

1 回答 1

1

经过一番思考,我认为这个加入会起作用。

class Events
  def get_users

User.joins(%"inner join interests on interests.user_id = users.id
             inner join categories_interests
               on categories_interests.interest_id = interests.id
             inner join categories on categories_interests.category_id = categories.id
             inner join interests_locations
               on interests_locations.interest_id = interests.id
             inner join locations on interests_locations.location_id = locations.id
             inner join categories_events on categories_events.category_id = categories.id
             inner join events_locations on events_locations.location_id = locations.id
             inner join events
               on categories_events.event_id = events.id
               and events_locations.event_id = events.id").where("events.id = :eid", :eid => id)

  end
end
于 2012-09-25T10:07:43.843 回答