Rails和Mongoid的动态属性 [英] Dynamic attributes with Rails and Mongoid
问题描述
我正在通过带有Rails的Mongoid Ruby宝石学习MongoDB(Rails 3 beta 3),我试图提出一种基于另一个模型的字段在模型上创建动态属性的方法.无模式的数据库将是一个不错的选择.
I'm learning MongoDB through the Mongoid Ruby gem with Rails (Rails 3 beta 3), and I'm trying to come up with a way to create dynamic attributes on a model based on fields from another model, which I thought a schema-less database would be a good choice for.
例如,我有以下模型:
class Account
include Mongoid::Document
field :name, :type => String
field :token, :type => String
field :info_needed, :type => Array
embeds_many :members
end
class Member
include Mongoid::Document
embedded_in :account, :inverse_of => :members
end
我希望采用Account模型的"info_needed"属性,并根据其内部内容在Member模型上创建动态属性.如果club.info_needed是["first_name","last_name"],则我正在尝试创建一个将first_name和last_name属性保存到成员模型的表单.
I'm looking to take the "info_needed" attribute of the Account model and created dynamic attributes on the Member model based on what's inside. If club.info_needed was ["first_name", "last_name"], I'm trying to create a form that would save first_name and last_name attributes to the Member model.
但是,在实践中,尝试执行此操作时,我在Member模型上始终收到未定义的方法first_name =错误.我知道MongoDB可以处理每条记录的动态属性,但是如何让Mongoid做到这一点而又没有未定义的方法错误?
However, upon practice, I just keep getting "undefined method first_name=" errors on the Member model when trying to do this. I know MongoDB can handle dynamic attributes per record, but how can I get Mongoid to do this without an undefined method error?
推荐答案
Mongoid并不真正支持它.
Mongoid doesn't really support it.
我碰巧有.
I happen to have asked this at Mongoid group myself.
创建新文档时可能是这样的,
It is possible when you create new document, like this:
account = Account.new(:some_dynamic_field => "...")
这篇关于Rails和Mongoid的动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!