2014-07-10 58 views
0

我在mongodb中有一個用於存儲參與者的集合。數據是這樣:通過Object_id搜索mongoid中的文檔

{ 
    "_id" : ObjectId("53badeee6d6179191f030000"), 

    "user_id" : ObjectId("53b619a16d6179141e000000"), 

    "campaign_id" : ObjectId("53b82c246d617912a9040000") 
    } 

現在我該怎樣從軌搜索呢? - 這是行不通的。我就應該總是創建這樣的對象:ObjectId("53b82c246d617912a9040000")

參與者模型:

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 

難道我做錯了由設計本身?請建議。

+0

請張貼您的模型,以便我們瞭解用戶,廣告系列和參與者之間的關係。 – tirdadc

+0

增加了模型 –

+0

http://two.mongoid.org/docs/querying/finders.html –

回答

0

使用

@participant = Participant.where(
    user_id: current_user_id, 
    campaign_id: params[:id] 
).first 

@participant = Participant.where(
    user_id: current_user.id, # as i suspect you are using devise current user 
    campaign_id: params[:id] 
).first 

,它應該工作。還請確保params[:id]包含現有的campaign_id,並且您沒有使用錯誤的參數搜索(例如,params[:campaign]