从代码内生成Rails模型(从控制器调用生成器)

我特别需要能够从代码中调用Rails命令(即发生某些操作时)。 我需要使用特定字段创建模型(由表单确定)并最终运行创建的迁移。

所以这个表单我会创建所有字段,然后创建一个带有某些字段(表和列)的模型

那么,有没有办法调用rails generate model NAME [field[:type][:index] field[:type]bundle exec rake db:migrate从控制器/ ruby​​代码中bundle exec rake db:migrate

而不是每个类别有一个表,这是一个更关系数据库y方法:

 create table category ( id serial primary key, name text not null ); create table attribute ( id serial primary key, name text not null ); create table item ( id serial primary key, category_id integer not null references category (id), description text ); create table category_attribute ( attribute_id integer not null references attribute (id), category_id integer not null references category (id) ); create table item_attribute ( attribute_id integer not null references (attribute.id), item_id integer not null references item (id), value text ); 

创建类别时,将其名称(以及任何其他一对一属性)存储在category表中。 确保attribute表具有该类别具有的每个属性的条目,然后使用category_attribute表将这些属性链接到该类别。

添加类别的新成员时,可以使用item表来存储有关项目的主要内容,并使用item_attribute表来存储其每个属性的值。 因此,对于您提到的汽车和宠物方法,您的数据库可能看起来像

 category id | name ----+------ 1 | car 2 | pet attribute id | name ----+------------ 1 | make 2 | breed 3 | model_year 4 | name category_attribute attribute_id | category_id --------------+------------- 1 | 1 2 | 2 3 | 1 4 | 2 item id | category_id | description ----+-------------+---------------- 1 | 1 | Hyundai Accent 2 | 2 | Fuzzy kitty item_attribute attribute_id | item_id | value --------------+---------+--------- 1 | 1 | Hyundai 3 | 1 | 2007 2 | 2 | DSH 4 | 2 | Sam 

这种方法可能感觉非常明显,因为它与Rails模型使用的“具有多个属性的一个对象”样式不匹配。 但是,这就是关系数据库的工作方式。 我相信你可以做一些ActiveRecord魔术来使对象/关系翻译更加自动,但我不记得它现在被称为什么。