加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 用于模型中动态自定义字段的Rails gem / plugi

发布时间:2020-12-17 04:16:20 所属栏目:百科 来源:网络整理
导读:ruby on rails上是否有gem / plugin,它能够在运行时在模型中定义自定义字段,而无需为每个不同的字段更改模型本身. 我正在寻找像Redmine acts_as_customizable插件这样的东西,它被封装成可用于轨道方式的宝石,即 gem 'gemname'rails g somethingrails db:migr
ruby on rails上是否有gem / plugin,它能够在运行时在模型中定义自定义字段,而无需为每个不同的字段更改模型本身.

我正在寻找像Redmine acts_as_customizable插件这样的东西,它被封装成可用于轨道方式的宝石,即

gem 'gemname'
rails g something
rails db:migrate

class Model < ActiveRecord::Base
  acts_as_something
end

以下是Redmine中使用的CustomField和CustomValue类.

编辑:

由于我的问题不明确,我添加了一个简短的用例,更好地解释了我的需求:

I want users to be able to design their own forms,and collect data
submitted on those forms. An important decision is the design of how
these custom dynamic records are stored and accessed.

从here开始,在本文中用不同的思路来解决问题,但它们都有缺点.出于这个原因,我问是否已经在一些宝石中找到了问题,而无需重新考虑整个问题.

解决方法

我担心在ActiveRecoand中执行它可能会非常棘手和复杂(通常在标准关系数据库中).看看 http://mongoid.org/docs/documents/dynamic.html – 这个机制正在使用nosql功能.

您也可以尝试以下技巧:

1 /使用数据库列中的自定义字段序列化哈希值,例如{:foo => ‘bar’,:fiz => ‘biz’}

2 /从数据库加载记录后,执行一些元编程并在记录的单例类上定义相应的方法(假设自定义字段在custom_fields列中存储和序列化):

after_initialize :define_custom_methods
# ..or other the most convinient callback

def define_custom_methods
  # this trick will open record's singleton class
  singleton_class = (class << self; self; end)
  # iterate through custom values and define dynamic methods
  custom_fields.each_with_key do |key,value|
    singleton_class.send(:define_method,key) do
      value
    end
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读