【问题标题】:Rails3: Find records that have a relationship but exclude some by a specific valueRails3:查找具有关系但按特定值排除某些记录的记录
【发布时间】:2013-11-25 20:24:42
【问题描述】:

你好有两个模型(Rails3)

阿姨 朋友

在哪里

阿姨 :has_many => 朋友

朋友 :belongs_to => 阿姨

现在,我想获取所有与朋友 X 无关的阿姨

我尝试了类似的方法:

Aunt.includes(:friends).where('friends.id != ? ', X )

但它不起作用。

PS:我还需要包括没有任何朋友关联的阿姨。

这是 :

的输出
@results = Aunt.custom(true).select('aunts.id, aunts.goal').joins("LEFT OUTER JOIN friends r ON aunts.id = r.aunt_id").where('r.other_value != ? or r.id is NULL', 4259 ).ordered_by_status_creation.select('aunts.id, aunts.goal')

SELECT aunts.id, aunts.goal FROM aunts LEFT OUTER JOIN friends r ON aunts.id = r.aunt_id WHERE aunts.deleted_at 为空且 leads.type IN ('MyType') AND (is_custom = 1) AND (r.another_value != 4259 or r.id is NULL) ORDER BY status desc, aunts.id desc

有什么想法吗?

【问题讨论】:

  • Aunt.joins(:childrens).where('childrens.id ? ', X ) 给你什么?
  • 返回所有阿姨@rainkinz

标签: ruby-on-rails-3 activerecord


【解决方案1】:

你可以使用如下范围

范围 :without_house, lambda { |param|参数? {:conditions => ["related_id != ?", param.id]} : {} }

【讨论】:

    【解决方案2】:

    我认为你需要这样的东西:

    Aunt.joins("LEFT OUTER JOIN friends ON aunts.id = friends.friend_id").where('friends.id != ? or friends.id is NULL', X ).select
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      相关资源
      最近更新 更多