gpt4 book ai didi

ruby-on-rails - 在 Rails 中通过 belongs_to 关系查询记录

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:18 24 4
gpt4 key购买 nike

我有一个事件模型,它们属于一个位置

如何选择 location.country = Australia 的所有事件? (例如)

我可以在一个范围内这样做吗?

最佳答案

使用最新的 rails 版本,您可以:

Activity.joins(:location).where(locations: { country: "Australia" })

注意:

  • 它是 joins(:location) 中的位置(单数),因为它引用了 belongs_to 关系名称
  • 它是 where(…) 中的位置(复数),因为它引用了表名

后者意味着如果您有以下情况:

belongs_to :location, class_name: "PublicLocation"

查询将是:

 Activity.joins(:location).where(public_locations: { country: "Australia" })

关于ruby-on-rails - 在 Rails 中通过 belongs_to 关系查询记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com