加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails中,使用Mongoid,如何找到具有有效(非零

发布时间:2020-12-16 19:02:21 所属栏目:百科 来源:网络整理
导读:所以我有两个这样的模特 class ModelParent include Mongoid::Document field :name,:type = String has_one :model_childendclass ModelChild include Mongoid::Document field :name,:type = String belongs_to :model_parentend 假设我在rails控制台中有
所以我有两个这样的模特
class ModelParent
  include Mongoid::Document
  field :name,:type => String
  has_one :model_child
end

class ModelChild
  include Mongoid::Document
  field :name,:type => String
  belongs_to :model_parent
end

假设我在rails控制台中有一个名为mp的持久化ModelParent实例

mc = mp.create_model_child(:name=>"child")

然后呢

mp.model_child

它返回一个有效的对象

但是,如果我像这样搜索它:

ModelParent.where(:model_child.ne => nil).length

它返回0

我已经尝试创建model_child然后使用build_model_child()进行分配,并且每个方法都显示model_child显然在父级中,但是非nil(.ne)的查询无法找到所有带子级的ModelParents.

我究竟做错了什么?

更新:

回答我自己的问题.我仍然不确定为什么:model_child.ne => nil不起作用,但……

我通过编码这样的代码来解决问题:

def self.with_child
    user_ids = ModelChild.all.only(:model_parent_id).map(&:model_parent_id)
    return ModelParent.where(:_id.in => user_ids).all
  end

解决方法

它不起作用,因为外键存储在属于关系的一侧.因此,在您的情况下,ModelChild集合将具有字段model_parent_id,而不是相反.我猜你已经想到了这一点,但是我没有像你那样解决它,我建议你切换has_one和belongs_to关联,然后使用:
ModelParent.where(:model_child_id.ne => nil)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读