开发者

How to retrieve and exclude some ids from an ActiveRecord query?

I have a User object, and an Alliance object, where User has_many :alliances, and Alliance belongs_to :user. I want to get a list of users, but exclude those users with whom the current_user already has an active alliance (if the user already has an alliance, the :pending field will be false).

Here's开发者_StackOverflow社区 a concrete example. Suppose our users are Joe, Bob and Jill. Joe and Jill are active allies, so Joe.alliances will include Jill, and Jill,alliances will include Joe. I want a list of all users that exclude alliances for the current user, so if Joe is current_user, then I want an array of User objects that does not include Jill, but does include Bob.

In code, what I have so far:

# Get all users
user_list = User.all

# Get alliances that are not pending
active_alliances = current_user.where(:pending => false)

Now, I was thinking of using this tip to exclude from user_list the active_alliances. So, what I need to do is extract from active_alliances a single-dimensional array with nothing other than a list of user_ids. I'm thinking something like:

# Select just the :ally field (which contains the user_id of the ally)
alliance_id_list = current_user.all(:select => "ally")

This last isn't quite what I want, because it gives me a hash. Now, I could just iterate through the hash, but I'm thinking that might not be the best way. Is there a direct method to do this? Perhaps by setting a negative conditional for the query? Thanks.

Update: See this question for more details on how to solve this problem; it can be used in connexion with the .collect method suggested below.


I'm not sure I'm reading your question correctly, but it looks like you just need to collect the alliance user ids:

User.where("ally not in ?", current_user.alliances.collect(&:user_id))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜