开发者

how to say 'is not in' in an active record query

Hey I hope you can help me,

@courses = Course.where(:id != current_user.courses)

I want to get the courses, where the current user is not registered to

@c开发者_StackOverflowourses = Course.where(:id => current_user.courses) gives me the courses where the user has registered to. But I want the opposite

Associations are just fine. I can use current_user.courses or current_user.assignments.


You probably need something like this:

@courses = Course.where("id NOT IN (?)", current_user.courses)

The reason you can't use a pure array or hash condition is because you're negating ("NOT IN") the query. As far as I know, this can't be done without using the string based syntax. If you just wanted to find matching ("IN") items, you could use the hash form:

@courses = Course.where(:id => current_user.courses)

It's the negating ("NOT IN") part that makes it tricky.

More information can be found in the Active Record Query Interface Guide.


If you wish to avoid using raw strings, you could use ARel

@courses = Course.where(Course.arel_table[:id].not_in(current_users.courses))

Unfortunately, ARel is not documented very well. I use this as a reference.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜