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

时间:2014-12-07 12:04:45

标签: ruby-on-rails ruby ruby-on-rails-4

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

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

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

1 个答案:

答案 0 :(得分:1)

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

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魔术来使对象/关系翻译更加自动化,但我不记得它现在所调用的内容。

相关问题