怎么说在活动记录查询中'不在'

dan*_*iel 2 activerecord ruby-on-rails-3

嘿,我希望你能帮助我,

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

我想获得当前用户未注册的课程

@courses = Course.where(:id => current_user.courses)为我提供了用户注册的课程.但我希望相反

协会就好了.我可以使用current_user.courses或current_user.assignments.

mar*_*ada 6

你可能需要这样的东西:

@courses = Course.where("id NOT IN (?)", current_user.courses)
Run Code Online (Sandbox Code Playgroud)

你不能使用纯数组或散列条件的原因是因为你否定了("NOT IN")查询.据我所知,如果不使用基于字符串的语法,就无法做到这一点.如果您只想查找匹配("IN")项,则可以使用哈希表单:

@courses = Course.where(:id => current_user.courses)
Run Code Online (Sandbox Code Playgroud)

否定("NOT IN")部分使其变得棘手.

可以在" Active Record查询接口指南"中找到更多信息.