【问题标题】:rails 3 dynamically create a model with attributes that are stored in a database tablerails 3 动态创建具有存储在数据库表中的属性的模型
【发布时间】:2011-06-22 14:59:32
【问题描述】:

我正在创建一个 ruby​​ on rails 应用程序,该应用程序存储用户最喜欢的出版物,并且偶然发现了一个问题并需要一些帮助。

用户可以添加任意数量的不同类型的出版物,例如书籍、电影、报纸、文章等。每种出版物类型都有不同的属性,例如书籍可能有作者和出版商,以及电影可能有导演和制片人。一个出版物有许多属性。

我的应用目前看起来像这样:我有一个存储出版物类型的publications资源。有一个名为 attribs 的资源,它存储特定出版物的所有属性。最后还有第三种资源,称为收藏夹

class Publication < ActiveRecord::Base
 has_many :attribs

 # columns in this model => name, hidden

 # example ( :name => "movie", :hidden => false )
end

class Attrib < ActiveRecord::Base
 belongs_to :publication

 # columns in this model => publication_id, name, datatype

 # example (:publication_id => 1, :name => "Movie Title", :datatype => "string")
 # example (:publication_id => 1, :name => "Director", :datatype => "string")
end

class Favourite < ActiveRecord::Base

 # columns in this model => data, reason

 # example (:data => "[serialized form data]", :reason => "some reason why its a fav")

end

当用户创建新收藏并选择出版物时,我希望生成一个表单,其中包含用户为该特定出版物选择的属性。

有没有一种方法可以动态创建具有存储在数据库表中的属性的模型/表单?

Formtastic 是一个动态表单生成器,可以用来创建表单吗?

对我来说,这似乎过于复杂,但如果我的应用程序中没有大量表,我想不出另一种方法。

【问题讨论】:

    标签: ruby-on-rails dynamic attributes model formtastic


    【解决方案1】:

    Formtastic 和 Simple Form gem 需要一个模型来为您生成表单。看看这个帖子here。创建无表模型。然后使用无表模型创建一个临时模型。然后从包含该模型的列值的表中获取临时模型的列,就像在该链接中为 Foo 所做的那样。使用 Temporary Class 的实例,您可以使用 Formtastic 并为其生成表单。

    【讨论】:

      【解决方案2】:

      我认为你可以自己实现它。

      @publication.attribs.each do |attrib|
        case attrib.datatype
        when "string"
          f.text_field attrib.name
        when "text"
          f.text_area attrib.name
        when "password"
          f.password_field attrib.name
        ...
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-03
        • 2010-11-29
        • 2011-08-01
        • 1970-01-01
        • 2011-11-05
        • 2015-07-19
        • 2019-03-15
        • 1970-01-01
        相关资源
        最近更新 更多