【问题标题】:A has_one psudorelationship that returns the last of a has_many relationship?返回 has_many 关系的最后一个的 has_one 伪关系?
【发布时间】:2014-10-09 20:23:58
【问题描述】:

我想在Model 类上建立关联。 Modelhas_manyOtherModels。我想在Modelhas_one :last_other_model 上建立关联。

我能想到的最好的办法是做has_one :last_other_model, class: 'OtherModel', limit: 1——但has_one不接受limit

有什么想法吗?

【问题讨论】:

  • 你可以使用范围吗?甚至是返回 activerecord 关系的方法?为什么它需要是一个协会?
  • 渴望加载它,我不相信你可以渴望加载范围(但我可能错了)。
  • 搜索急切加载范围导致了这一点:stackoverflow.com/questions/7937759/… 这似乎做了我想做的事情,但使用了has_many。这可能是干净地做到这一点的唯一方法;但问题是,以防有人有聪明的方法:]
  • 啊,但是 rails 说急切加载会忽略 has_many 的限制,这会破坏目的: > 如果急切加载带有指定 :limit 选项的关联,它将被忽略,返回所有关联对象:

标签: ruby-on-rails activerecord


【解决方案1】:

Rails 4,试试:

has_one :last_other_model, ->{ order 'some_field asc'}, class_name: 'OtherModel'

第二个参数是一个 lambda,您可以在其中调用任何 ActiveRecord 方法进行过滤和排序,Rails 将返回该集合的第一个,而无需使用 limit

您也可以将其翻译成 Rails 3 和 2,当然语法完全不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多