2017-06-01 217 views
1

我有一個應用程序,用戶可以創建很多旅行,並且他們可以邀請他們的Facebook好友。在旅行證件中,有一個字段「參與者」是一個嵌入文件,Participant模型嵌入在Travel模型中。 exampleRails Mongoid:查詢嵌入式文檔並訪問Mongoid標準

這裏是我的模型:

class Travel 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    # relations 
    belongs_to :user 

    # fields 
    field :title, type: String 
    field :description, type: String 
    field :begin_date, type: Date 
    field :end_date, type: Date 
    field :budget, type: Integer 
    field :go_back, type: Boolean 
    field :title_namespace, type: String 

    # friends 
    embeds_many :participants 
    accepts_nested_attributes_for :participants 

end 

class Participant 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :name, type: String 
    field :user_id, type: String 

    # relations 
    embedded_in :travel, :inverse_of => :participants 

end 

當我嘗試顯示,用戶已經被邀請旅遊,和這個請求:

@travel_participations = Travel.where('participants.user_id' => @user.id) 

我沒有任何結果,即使如果我在byebug有這條線:

#<Mongoid::Criteria 
    selector: {"participants.user_id"=>BSON::ObjectId('592c8da58511989ec850921e')} 
    options: {} 
    class: Travel 
    embedded: false> 

所以當我把這個在我的觀點:

<% unless @participations.nil? %> 
    <% @travel_participations.each do |travel_participation| %> 
    <p> <%= travel_participation.title %> </p> 
    <% end %> 
<% end %> 

我試圖與.all.first.to_a.as_json,沒有結果......有些人知道問題出在哪裏?

回答

1

你在你的嵌入式型號有這樣的:

field :user_id, type: String 

,您的查詢使用BSON::ObjectId

Travel.where('participants.user_id' => @user.id) 

爲原始查詢顯示:

selector: {"participants.user_id"=>BSON::ObjectId('592c8da58511989ec850921e')} 

嵌入式文件可能有一個字符串字段如:

"user_id": "592c8da58511989ec850921e" 

而非ObjectId你正在尋找:

"user_id": ObjectId("592c8da58511989ec850921e") 

所以你不會找到你要找的內容,由於類型不匹配。

無論是解決嵌入式領域的類型:

field :user_id, type: BSON::ObjectId 

或查詢它,因爲它是字符串:

Travel.where('participants.user_id' => @user.id.to_s) 

更改類型將包括修復了什麼數據,你已經有了,更改查詢以不同的方式醜陋。

有時Mongoid會爲你轉換字符串和ObjectIds,有時它不會。當我用我Mongoid修補to_bson_id方法爲BSON::ObjectIdStringMongoid::Document ......這樣我就可以說這樣的話:

Model.where(:some_id => some_id.to_bson_id) 

,而不必時時擔心什麼類型some_id了。我還確保所有ID字段始終指定爲BSON::ObjectId

+1

完美的答案,很明顯,我有解釋,很多朋友的感謝!我將你的答案標記爲已接受! –

+1

那麼,沒有解釋的答案不會很多,是嗎?字符串和ObjectIds之間的區別非常煩人。 –