微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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中使用的CustomFieldCustomValue类.

编辑:

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

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

原文地址:https://www.jb51.cc/ruby/268251.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐