简体   繁体   English

Rails ActiveRecord与数组连接

[英]Rails ActiveRecord join with an array

I'm trying to create an ActiveRecord query in my Rails application that involves an inner join of two tables, though one of the records I'm trying to join on is an serialized array (string). 我正在尝试在涉及两个表的内部联接的Rails应用程序中创建ActiveRecord查询,尽管我尝试联接的记录之一是序列化数组(字符串)。 For example, I have three tables in total. 例如,我总共有三个表。 The associations look like this: 关联如下所示:

  • Car: 汽车:

     serialize :categories_id, Array belongs_to :postings belong_to :categories 
  • Category: 类别:

     has_many :cars has_many :postings, through: :cars 
  • Posting 发帖

     has_many :categories, through: :cars has_many :cars 

This is my cars table (notice the array): 这是我的cars表(注意数组):

select cars.* from cars

id: 23,
posting_id: 10,
categories_id: [1, 5, 20]

This is my categories table: 这是我的categories表:

select categories.* from categories

id: 20,
name: "BMW"

This is my postings table: 这是我的postings表:

select postings.* from postings

id: 20,
title: "First title",
description: null,
value: "open"

The join I want to create is similar to this: 我要创建的联接与此类似:

select categories.* from categories inner join cars on categories.id = 
cars.categories_id where cars.posting_id = 20

Except right now it's not returning any results, because the join on cars.category_id is an array. 除了现在,它不会返回任何结果,因为cars.category_id上的联接是一个数组。 I'm basically wanting to return all the associated categories from the categories_id column in the cars table. 我基本上是想从cars表中的categories_id列返回所有关联的categories Any ideas on how to do this? 有关如何执行此操作的任何想法?

Official document for ActiveRecord serializer specifies that the serialized attribute will be saved as YAML in the database. ActiveRecord序列化程序的官方文档指定,序列化的属性将在数据库中另存为YAML。 When you save the record or fetch the record the serailization and deserialization of the attribute to proper type(array in your case) happens on the ruby activerecord layer, not handled as array on the database layer. 当您保存记录或获取记录时,将属性的序列化和反序列化为正确的类型(在您的情况下为数组)发生在ruby activerecord层上,而不是在数据库层上作为数组处理。 This is the downside of using serialized attributes and we can are pretty much limited to loading and saving the data. 这是使用序列化属性的不利之处,我们只能局限于加载和保存数据。

You can normalize your data with a new association has_and_belongs_to_many using cars_categories table to support your usecase. 您可以使用cars_categories表通过新的关联has_and_belongs_to_many来规范化数据,以支持您的用例。 cars_categories table can help you using through relation. cars_categories表可以帮助您通过关联使用。

cars 汽车

belongs_to :postings   
has_many :cars_categories
has_many :categories, through: :cars_categories,  :source => :category

category 类别

has_many :postings, through: :cars
has_many :cars_categories
has_many :cars, through: :cars_categories,  :source => :car

Hope this helps. 希望这可以帮助。

Please refer this answer as well. 请同时参考此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM