【问题标题】:Find first record that does not belong to a certain grandparent查找不属于某个祖父母的第一条记录
【发布时间】:2014-01-01 13:38:57
【问题描述】:

三种型号:

class Subscription < ActiveRecord::Base
  belongs_to :plan
end

class Plan < ActiveRecord::Base
  has_many :subscriptions, dependent: :destroy
  belongs_to :plan_category
end

class PlanCategory < ActiveRecord::Base
  has_many :plans
end

我有一个subscriptions 的集合,并且想用title: "unwanted" 查找没有PlanCategory“祖父母”的最新集合。

这是我的愚蠢尝试(在很多地方都是错误的):

Subscription.joins(plan: :plan_category).where.not(title: "unwanted")

如果这对于常见的 Rails 方法是不可能的,我正在寻找一个循环,当找到第一个合适的记录时退出。但同样,我还是个新手,无法理解如何构建这样的循环。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 associations


    【解决方案1】:
    Subscription.joins(:plan => :plan_category).where("plan_categorys.title != 'unwanted'")
    

    【讨论】:

    • 好极了,请只改“category”的复数拼写。
    • 在@Gjaldon 的帮助下,这是一个 Rails 4 版本:Subscription.joins(:plan =&gt; :plan_category).where.not(plan_categories: {title: "unwanted"}).last
    【解决方案2】:

    这是一个长版本:

    Subscription.joins(%q[
      INNER JOIN plans ON plans.id = subscriptions.plan_id
      INNER JOIN plan_categories ON plan_categories.id = plans.id
    ]).where.not(plans: { plan_categories: { title: "unwanted" }}).order("created_at").last
    

    还有一个我没有测试过的较短版本:

    wanted_plans = Plan.joins(:plan_categories).where.not(plan_categories: { title: "unwanted" })
    Subscription.joins(:plans).merge(wanted_plans).order("created_at").last
    

    希望有帮助!

    【讨论】:

    • 非常感谢您提供 Rails 4 语法。看看我对我所采用的解决方案的其他答案的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多