简体   繁体   中英

Search document in mongoid by Object_id

I have a collection in mongodb to store Participants. 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")

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM