简体   繁体   中英

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). 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):

select cars.* from cars

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

This is my categories table:

select categories.* from categories

id: 20,
name: "BMW"

This is my postings table:

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. I'm basically wanting to return all the associated categories from the categories_id column in the cars table. 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. 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. 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 table can help you using through relation.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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