【问题标题】:How can I include a column from a join table in a rails association?如何在 rails 关联中包含连接表中的列?
【发布时间】:2019-10-03 20:54:31
【问题描述】:

我正在使用连接表连接两个模型,以便我可以在关系上添加状态:

class Test < ApplicationRecord
  has_many :products_tests
  has_many :products, through: :products_tests

  def products_with_status
    products_tests = ProductsTest.includes(:product).where(test_id: id)
    products_tests.map do |products_test|
      products_test.product.as_json.merge(status: products_test.status)
    end
  end

end

class Products < Application Record
  has_many :products_tests
  has_many :tests, through: :products_tests
end

class ProductsTest < ApplicationRecord
  belongs_to :product
  belongs_to :test
end

ProductTest 上有一个 status 列,让我在每次测试时将产品从“活动”切换为“暂停”。

当我使用来自Testproducts 关联时,我想在status 列中合并。我已经将上面的products_with_status 一起破解了,但想知道是否有更多“Rails”方式来做到这一点。

谢谢!

【问题讨论】:

  • 合并后要保存吗?另外,为什么要合并它,因为连接表中始终存在状态列?最后,在 Test 类中,不使用 active_record 查询就不能访问products_tests 吗?
  • 我正在对数据进行非规范化以通过网络发送它。它存储在客户端的 Redux 中,因此它“持久化”在那里。 TBH,我更喜欢让 Redux 完全 与 postgres 相同,但这是一个快速而肮脏的解决方案 :)

标签: ruby-on-rails associations jointable


【解决方案1】:

您可以添加一个新的has_many 关联

has_many :products_with_status, -> { joins(:products_tests).select("DISTINCT products.*, products_tests.status") }, through: :products_tests, class_name: "Product", source: :product

那你就可以了

Test.find(1).products_with_status.first.status

【讨论】:

  • 很遗憾,这会返回错误的记录数。
  • 在选择语句中添加DISTINCT。我已经更新了代码
  • 我认为问题在于joins(:products_tests) 是多余的,因为该关联也有through: :products_tests。没有joins,我想我得到了正确的结果。谢谢!
猜你喜欢
  • 2011-06-01
  • 2023-03-29
  • 2012-05-06
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多