ruby-on-rails - 数据模型的动态自定义字段

标签 ruby-on-rails ruby

我正在创建一个动态数据库,用户可以在其中创建资源类型,他/她可以在其中添加自定义字段(多个文本、字符串和文件)

每种资源类型都能够显示、导入、导出其数据;

我一直在考虑这个问题,下面是我的方法。我很想听听你们的想法。

想法:

  1. 只是散列数据字段中的所有自定义数据(优点:写入更容易,缺点:读出可能更难);

  2. 子字段(模型会有多个字符串字段、文本字段和文件路径字段);

  3. 同一表中固定数量的自定义字段,键映射数据散列存储在同一行中;

  4. 非 SQL 方法,但问题是动态生成/更改模型以处理不同的自定义字段;

最佳答案

首先你可以创建几个模型:
- 字符串数据
- bool 数据
- 文本数据
- 文件数据
等(您需要的所有数据和字段格式)

每个模型都会引用一些项目,其中将包含有关字段的信息

即:

class Project < ActiveRecord::Base
  has_many :project_fields
  has_many :string_datas :through => project_fields
  has_many :file_datas :through => project_fields
  has_many :boolean_datas :through => project_fields
  etc ...
end

class ProjectField < ActiveRecord::Base
  # title:string field_type:string project_id:integer name:string
  belongs_to :project
  has_many :string_datas
  has_many :file_datas
  has_many :boolean_datas
  etc ...
end

class StringData < ActiveRecord::Base
  # data:string project_field_id:integer
  belongs_to :project_field, :conditions => { :field_type => 'String' }
end

class FileData < ActiveRecord::Base
  # data:file project_field_id:integer
  belongs_to :project_field, :conditions => { :field_type => 'File' }
end

project = Project.new
project.project_fields.new(:title => "Product title", :field_type => "String", :name => 'product_title')
project.project_fields.new(:title => "Product photo", :field_type => "File", :name => 'product_photo')
project.save

<% form_for project do |f| -%>
  <% project.project_fields.each do |field| -%>
    <%= field_setter field %>
    #=> field_setter is a helper method wich creates form element (text_field, text_area, file_field etc) for each type of prject_field
    #=> ie: if field.field_type == 'String' it will return
    #=> text_field_tag field.name => <input name='product_name' />
  <% end -%>
<% end -%>

并创建(更新)方法

def create
  project = Project.new(params[:project])
  project.project_fields.each do |field|
    filed.set_field params[field.name]
    # where set_field is model method for setting value depending on field type
  end
  project.save
end

它没有经过测试和优化,只是展示了您可以实现它的方式。

更新:我已经更新了代码,但它只是模型,你必须自己考虑一下 :) 你可以尝试找出另一个实现

关于ruby-on-rails - 数据模型的动态自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2593371/

相关文章:

ruby-on-rails - 如何在没有 ActiveRecord 的情况下在 Redis 和 Ohm 上使用表单?

ruby-on-rails - curl 在 Ruby on Rails 应用程序上上传文件

Ruby-on-Rails 重命名变量测试仍然看到以前的名称

javascript - 如何简单初始化一个前十个整数的数组?

Ruby:配置文件解析器与OptionParser结合

ruby-on-rails - 为什么应该将 "hard"部署到生产环境中才能部署Ruby on Rails?

ruby-on-rails - 为什么不 bundle 安装带有扩展名的本地 gem?

mysql - ActiveModel::MissingAttributeError: 无法写入未知属性 `user_id`

Ruby 在同一行上多次打印

ruby-on-rails - Heroku - bundler : failed to load command: unicorn