0

I have a hash with members of an appointment and try to create a MySQL query in my rails controller. The users with the ids from the map command e.g. {1,3} should be excluded in the query. So for example @appointment.members.map{|m| m.user_id} returns {1,3,5} and I'd like to find all other users but these.

@users = User.where( "id NOT IN (?)", @appointment.members.map{|m| m.user_id} )

I'm using Rails 3.2.9 so maybe my exclude statement is wrong cause I don't get any result out of this query. The problem can't be the map array - I already tested that. Thanks in advance.

4
  • What is the error with the generated query? Commented Dec 10, 2012 at 10:20
  • Thats the strange part - if I test the query in the rails console I get valid results but in the controller the @users instance variable is empty... Commented Dec 10, 2012 at 10:24
  • Is @appointment.members really a Hash or do you mean that it's a has_many relationship? Commented Dec 10, 2012 at 10:31
  • it's a has_many relationship Commented Dec 10, 2012 at 12:01

2 Answers 2

1

I think you just have a problem with the map method, try this:

@users = User.where( "id NOT IN (?)", @appointment.members.map(&:user_id) )

EDIT: removed the wrong syntax for future readers if any

Sign up to request clarification or add additional context in comments.

2 Comments

The first one returns just an empty array [], with the second one I get all users, including those in the .map array
The second one is not valid. The first one is
0

I solved the problem with a new instance variable:

@members = @appointment.members.all

and then

@add_users = User.where( "id NOT IN (?)", @members.map(&:user_id) )

thanks for the support

1 Comment

Then you can do @add_users = User.where( "id NOT IN (?)", @appointment.members.all.map(&:user_id) ) directly, but you know that perhaps?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.