alt
alt

Reputation: 13927

Best way to store an array of data associated with a post in Rails

So I have a MySQL-powered Rails app that has a post model, and I want each post to have a list of keyword associated with it. The keywords are very specific and it would be very rare that one keyword would be shared between two posts.

There are three options here:

  1. A comma separated list in a "keywords" attribute
  2. Have a serialized array in a "keywords" attribute
  3. Build a keyword model and store each keyword under its own record and associate them to posts with an ID

Which is the best solution and why?

Upvotes: 0

Views: 154

Answers (3)

fotanus
fotanus

Reputation: 20116

If you want to search for the tags, 3, because otherwise you would have to or instantiate every object in the search, or do a SQL like query which would be very ugly.

If you don't want to query for the tags, serialize it would make it readable and avoid a table (and eager loading) just for that.

Upvotes: 1

iltempo
iltempo

Reputation: 16012

In general the decision depends on what you are planning use this keyword list for. If you plan to do any kind of aggregation on multiple records, putting it into a single attribute (serializing or commas) will make your live hard. If not simplicity is always a good choice.

As mentioned by @Mori ActsAsTaggable is a good choice even though it works best for shared keywords (tags).

Upvotes: 0

Mori
Mori

Reputation: 27789

Four. ActsAsTaggableOn.

Keywords/tags are so useful you'll want to use them over and over again. You'd just be reinventing a wheel when good ones are lying around for free.

Upvotes: 1

Related Questions