Ruby on Rails: Aggregating several columns into an Array
I'm developing a Ruby on Rails app where one of my database tables has 10 columns (pile_1 through to pile_10). It would be convenient to access these columns in the model as a 10-element Array.
It feels like I should be able to coerce composed_of
into doing what I want, but I can't figure out how. Can anyone enl开发者_运维技巧ighten me, or suggest a better tactic?
Would
def piles
(1..10).map{ |num| self[ "pile_#{ num }"]}
end
not suffice?
Since you have the power to change the schema, you should. Storing an array as separate columns in a table is denormalized. Whether or not your schema is normalized might not matter to you, but your current difficulty is a direct result of a denormalized schema.
What you ought to do is to create a new table, piles, like so. I'll use postgres syntax, since that's what I know. I don't know the name of the table which currently contains all of the piles* columns, so I'll call it "foo":
create table piles (
id serial primary key,
foo_id int not null references foo(id),
value text not null,
);
Every column you now have in foo exists instead as a row in piles. In the model for piles, add:
belongs_to: foo
and in the model for foo, add:
has_many: piles
In your controller, once you have a foo in hand, you can access its piles with foo.piles
精彩评论