简体   繁体   中英

get records without records from another table

I want to get bicycles which are not disliked by user. So if user disliked a bicycle it will never show that bicycle again.

Bicycle has many dislikes and belongs to User. User has many dislikes and bicycles. Dislike belongs to User and Bicycle.

Here is my code in index action of BicyclesController:

@bicycles = Bicycle.includes(:dislikes).where.not("dislikes.author_id = #{current_user.id}")

So I am getting this error:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "dislikes"
LINE 1: ...cles" WHERE "bicycles"."published" = $1 AND (NOT (dislikes.a...
                                                             ^
: SELECT  "bicycles".* FROM "bicycles" WHERE "bicycles"."published" = $1 AND (NOT (dislikes.author_id = 1)) LIMIT $2 OFFSET $3

UPDATE

This query gives me records which are disliked by user:

@bicycles = Bicycle.includes(:dislikes).where(dislikes: {author_id: current_user.id})

But now I want to exclude these records from all. Is there an efficient way to do this?

PostgresSQL查询语法:

 @bicycles = Bicycle.includes(:dislikes).where.not(dislikes: {author_id:  current_user.id})

Finally I got needed result by:

user_dislikes = current_user.dislikes.map(&:bicycle_id)
@bicycles = Bicycles.where('id NOT in (?)', user_dislikes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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