Fetch posts from non blocking users

守給你的承諾、 提交于 2021-01-27 23:42:32

问题


I'm trying to fetch some posts from users that isn't blocking "me". Se models below:

User
  id
  username
  ....

Post
  id
  user_id
  content
  ...

Blockings
  blocker_id
  blocked_id

I need to fetch posts from all users that isn't blocking me.

I fetch all posts with:

@posts Post.all

But how do I joins this together.

Pseudo

SELECT * FROM posts WHERE "posts.user_id isn't blocking me"

I have a helper called current_user that returns the current logged in user "me".


回答1:


A way to do it with SQL would be:

select *
  from post
  where user_id not in 
    (select blocker_id 
    from blockings
    where blocked_id = 1);

Just replace the numerical id with the variable.

SQL Fiddle




回答2:


In your Post class and a scope like this :

scope :not_blocked_from, lambda{|user| where("blocked_id <> ?", user.id)}

And you can fetch those posts you want as below:

Post.not_blocked_from(me)

Will work.



来源:https://stackoverflow.com/questions/13155462/fetch-posts-from-non-blocking-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!