我有一个应用程序,用户可以创建许多旅游,他们可以邀请他们的facebook朋友。在旅行文档中,有一个字段“参与者”,即嵌入文档,即嵌入到Participant模型中的Travel模型。

以下是我的模特:
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,没有结果.有人知道问题出在哪里?
发布于 2017-06-01 21:11:33
在您的嵌入式模型中有这样的内容:
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::ObjectId、String、Mongoid::Document、.这样我就可以说:
Model.where(:some_id => some_id.to_bson_id)而不必总是担心some_id是什么类型。我还确保所有ID字段都指定为BSON::ObjectId。
https://stackoverflow.com/questions/44316985
复制相似问题