简体   繁体   中英

ActiveRecord schema for multiple types of objects with common columns?

I'm working on a Rails 5 app for Guild Wars 2, and I'm trying to figure out a way to serialize and store all of the items in the game without duplicating code or table columns. The game has a public API to get the items from, documented here: https://wiki.guildwars2.com/wiki/API:2/items

As you can see, all of the items share several pieces of data like ID, value, rarity, etc. but then also branch off into specific details based on their type.

I've been searching around for a solution, and I've found a few answers, but none that work for this specific situation.

  • Single Table Inheritance : There's way too much variance between items. STI would likely end up with a table over 100 columns wide, with most of them null.
  • Polymorphic Associations : Really doesn't seem to be the proper way to use these. I'm not trying to create a type of model that gets included multiple other places, I just want to extend the data of my "Item" model.
  • Multiple Table Inheritance : This looks to me like the perfect solution. It would do exactly what I'm wanting. Unfortunately, ActiveRecord does not support this, and all of the "workarounds" I've found seem hacky and weird.

Basically, what I'm wanting is a single "Item" model with the common columns, then a "details" attribute that will fetch the type-specific data from the relevant table.

What's the best way to create this schema?

One possible solution: Use #serialize on the details (text) column

class Item
 serialize :details, Hash
end

One huge downside is that this is very inefficient if you need to query on the details data. This essentially bypasses the native abstractions of the database.

I was in a similar situation recently. I solved by using Sequel instead of ActiveRecords. You can find it here: https://github.com/TalentBox/sequel-rails And an implmentation example: http://www.matchingnotes.com/class-table-inheritance-in-rails.html Good luck

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