我正在使用Mongoid并拥有一个项目和一个用户模型。 在Project模型中,我有一个字段
class Project
include Mongoid::Document
field :name
field :user_ids, :type => Array
end
class User
include Mongoid::Document
field :email
end
我可以找到属于一个项目的所有用户,即“找到该项目的用户”
@project = Project.first # => 'Housework'
User.criteria.id(@project.user_ids) # => ['Bart','Lisa','Maggie']
但是我找到属于一个用户的所有项目有点麻烦,即'找到这个用户的项目'
@user = User.first # => 'Bart'
Project.where(:user_ids => @user.id) # doesn't work
Project.where(:user_ids.includes => @user.id) # not such method
Project.where(:user_ids => [@user.id]) # doesn't make sense to compare arrays, but tried anyway and doesn't work
我知道你可以在User模型中有另一个字段来存储project_ids,我很乐意这样做,但我只是很好奇,有没有一种方法可以在查找条件中使用,与#includes类似?在红宝石?
答案 0 :(得分:0)
我找到了解决方法。它是all_in finder方法
示例:
Fruit.all[0].colors = ['red','green','blue'] #=> apple
Fruit.all[1].colors = ['yellow','green'] #=> banana
Fruit.all[2].colors = ['red', 'yellow'] #=> pineapple
要查找“颜色”数组字段中颜色为红色的所有水果,可以查询:
Fruit.all_in(:colors => ['red'])