问题
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