【问题标题】:Generate a Rails model from within code (invoke generator from a controller)从代码中生成 Rails 模型(从控制器调用生成器)
【发布时间】:2015-02-05 04:32:25
【问题描述】:

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

所以我的这个表单将创建所有字段,然后创建一个具有特定字段(表和列)的模型

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

【问题讨论】:

  • 你为什么有这个需求?我问是因为这听起来很成问题,也许有更好的方法来实现同样的目标。
  • 嗯,是的,也许我的解决方案有点太极端了。我需要实现的是:使用自己指定的信息字段创建多个类别(即汽车与宠物有不同的字段),一旦创建了这样的类别,我需要的命令将被调用,每个类别的新表将做出来。我知道我可以将所有字段存储为某种字符串,然后对其进行处理以正确显示它,但我需要为我的 Web 应用程序提供高级搜索功能,并且为每个类别创建单独的表似乎是实现它的最佳方式。我真的很想听听这个的替代品
  • 我肯定会寻求另一种解决方案 - 根据您的需要有很多潜在的解决方案 - 也许是 Rails serialize,或 Postgres hstore,或者像 category_fields 这样的单独表。在生产中生成模型和迁移似乎是一个痛苦的世界。我建议发布另一个问题,说明您要解决的问题和限制(例如,提供有关您的搜索需求的更多详细信息),我相信很多人都会有好的想法。
  • 我在这里问了另一个问题stackoverflow.com/questions/27342851/… ...问题是类别将在管理中创建,并且会非常谨慎地使用此功能。感谢您对我新创建的问题的意见。

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


【解决方案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 魔法来使对象/关系转换更加自动化,但我现在不记得它叫什么了。

【讨论】:

  • 我喜欢这种方法,但我不确定如何在 Rails 中实现。
  • 好吧,您可以从制作这些表和模型开始,然后在模型的辅助方法中手动进行链接。一旦你有一个工作的东西,复习一下 ActiveRecord 中可用的关联方法来清理它并使它变得更好。
猜你喜欢
  • 2011-11-18
  • 1970-01-01
  • 2014-07-14
  • 2014-11-23
  • 2011-05-04
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 2016-11-12
相关资源
最近更新 更多