简体   繁体   English

Rails-如何在这些表之间建立联接?

[英]Rails - how to make join between these tables?

I have these tables: 我有这些表:

users - contains list of all users in the system users-包含系统中所有用户的列表

cars - list of all cars, there is a column user_id cars-所有汽车的列表,其中有一列user_id

car_views - for tracking how many people visit profile of a car. car_views-用于跟踪有多少人访问汽车资料。 There are following columns: 有以下几列:

- car_id
- ip

I am trying to fetch the information, how many people saw cars of a respective user within a time period. 我正在尝试获取信息,在一段时间内有多少人看到了相应用户的汽车。 But my problem is, that I am not sure how can I fetch all views of cars from a respective user. 但是我的问题是,我不确定如何从各自的用户那里获取汽车的所有视图。

There would be a solution to put to the car_views table the column user_id , but it would be a duplication of information, or not? 可以将car_views表中的user_id列放入解决方案中,但这将是信息的重复吗?

You should be able to do something like this 你应该可以做这样的事情

user.cars.joins(:car_views).group('car_views.car_id').select('count(car_views.id) as count, car.name')

I'm not sure if this will work but you can give it a try 我不确定这是否行得通,但您可以尝试一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM