【发布时间】: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 列,让我在每次测试时将产品从“活动”切换为“暂停”。
当我使用来自Test 的products 关联时,我想在status 列中合并。我已经将上面的products_with_status 一起破解了,但想知道是否有更多“Rails”方式来做到这一点。
谢谢!
【问题讨论】:
-
合并后要保存吗?另外,为什么要合并它,因为连接表中始终存在状态列?最后,在 Test 类中,不使用 active_record 查询就不能访问
products_tests吗? -
我正在对数据进行非规范化以通过网络发送它。它存储在客户端的 Redux 中,因此它“持久化”在那里。 TBH,我更喜欢让 Redux 完全 与 postgres 相同,但这是一个快速而肮脏的解决方案 :)
标签: ruby-on-rails associations jointable