[英]Search document in mongoid by Object_id
I have a collection in mongodb to store Participants. 我在mongodb中有一个集合来存储参与者。 The data goes like: 数据如下:
{ "_id" : ObjectId("53badeee6d6179191f030000"), "user_id" : ObjectId("53b619a16d6179141e000000"), "campaign_id" : ObjectId("53b82c246d617912a9040000") }
Now how do I search it from rails? 现在如何从导轨中搜索它?
@participant=Participant.find(user_id:current_user_id, campaign_id:params[:id])
--This does not work. -这不起作用。 Should I always create objects like : ObjectId("53b82c246d617912a9040000")
我是否应该始终创建以下对象: ObjectId("53b82c246d617912a9040000")
Participant model: 参加者模型:
class Participant
include Mongoid::Document
field :detail, type: String
field :date, type: Date
belongs_to(:user)
belongs_to(:campaign)
validates_uniqueness_of :user, :scope => [:campaign]
end
Am i doing something wrong by design itself? 我本身是否在做错事? Please suggest. 请提出建议。
use 采用
@participant = Participant.where(
user_id: current_user_id,
campaign_id: params[:id]
).first
or 要么
@participant = Participant.where(
user_id: current_user.id, # as i suspect you are using devise current user
campaign_id: params[:id]
).first
and it should work. 它应该工作。 also make sure that the params[:id]
contains an existing campaign_id
and you are not searching with the wrong parameter ( params[:campaign]
for example) 还要确保params[:id]
包含现有的campaign_id
并且您搜索的参数不正确(例如params[:campaign]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.