Array Attribute for Ruby Model

前端 未结 5 2211
情书的邮戳
情书的邮戳 2021-01-30 14:19

Is it possible to create an attribute for a class that is an array? I tried reading this but I didn\'t get much out of it. I want to do something like this:

clas         


        
5条回答
  •  广开言路
    2021-01-30 14:38

    While you can use a serialized array as tokland suggested, this is rarely a good idea in a relational database. You have three superior alternatives:

    • If the array holds entity objects, it's probably better modeled as a has_many relationship.
    • If the array is really just an array of values such as numbers, then you might want to put each value in a separate field and use composed_of.
    • If you're going to be using a lot of array values that aren't has_manys, you might want to investigate a DB that actually supports array fields. PostgreSQL does this (and array fields are supported in Rails 4 migrations), but you might want to use either a non-SQL database like MongoDB or object persistence such as MagLev is supposed to provide.

    If you can describe your use case -- that is, what data you've got in the array -- we can try to help figure out what the best course of action is.

提交回复
热议问题