[英]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.