ruby-on-railsruby-on-rails-4mongoidmongoid3

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.


Solution

  • 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)