[英]Rails ActiveRecord join with an array
我正在嘗試在涉及兩個表的內部聯接的Rails應用程序中創建ActiveRecord查詢,盡管我嘗試聯接的記錄之一是序列化數組(字符串)。 例如,我總共有三個表。 關聯如下所示:
汽車:
serialize :categories_id, Array belongs_to :postings belong_to :categories
類別:
has_many :cars has_many :postings, through: :cars
發帖
has_many :categories, through: :cars has_many :cars
這是我的cars
表(注意數組):
select cars.* from cars
id: 23,
posting_id: 10,
categories_id: [1, 5, 20]
這是我的categories
表:
select categories.* from categories
id: 20,
name: "BMW"
這是我的postings
表:
select postings.* from postings
id: 20,
title: "First title",
description: null,
value: "open"
我要創建的聯接與此類似:
select categories.* from categories inner join cars on categories.id =
cars.categories_id where cars.posting_id = 20
除了現在,它不會返回任何結果,因為cars.category_id上的聯接是一個數組。 我基本上是想從cars
表中的categories_id
列返回所有關聯的categories
。 有關如何執行此操作的任何想法?
ActiveRecord序列化程序的官方文檔指定,序列化的屬性將在數據庫中另存為YAML。 當您保存記錄或獲取記錄時,將屬性的序列化和反序列化為正確的類型(在您的情況下為數組)發生在ruby activerecord層上,而不是在數據庫層上作為數組處理。 這是使用序列化屬性的不利之處,我們只能局限於加載和保存數據。
您可以使用cars_categories表通過新的關聯has_and_belongs_to_many來規范化數據,以支持您的用例。 cars_categories表可以幫助您通過關聯使用。
汽車
belongs_to :postings
has_many :cars_categories
has_many :categories, through: :cars_categories, :source => :category
類別
has_many :postings, through: :cars
has_many :cars_categories
has_many :cars, through: :cars_categories, :source => :car
希望這可以幫助。
請同時參考此答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.