使用Object.const_set创建Rails模型 [英] Creating rails model with Object.const_set

查看:63
本文介绍了使用Object.const_set创建Rails模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Neo4j在rails console中玩耍,并试图创建一个像这样的模型类:

I am playing around in the rails console with Neo4j and tried to create a model class like this:

Object.const_set("TestNode", Class.new(super_class=Neo4j::Rails::Model))
node = TestNode.new

如果我然后尝试使用node.save保存实例,则会收到一堆错误:

if i then try to save the instance with node.save I get a bunch of errors:

node.save
NoMethodError: undefined method `each' for nil:NilClass
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/attributes.rb:57:in `init_on_create'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/node_persistance.rb:16:in `create'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/callbacks.rb:39:in `create_with_callbacks'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/activesupport-3.2.8/lib/active_support/callbacks.rb:417:in `_run__1980184148__create__1722973119__callbacks'
from org/jruby/RubyKernel.java:2076:in `send'
...

如果我像平常一样创建TestNode类,一切都会正常工作

Everything works if I create the TestNode class like normal:

class TestNode < Neo4j::Rails::Model
end

创建模型类TestNode的第一种方法有什么问题?

What is wrong with the first way to create the model class TestNode?

我想到的目标是能够使用元编程动态创建新模型,然后将实例持久保存到neo4j数据库中.

The goal I have in mind is to be able to create new models on the fly using metaprogramming and then be able to persist instances to the neo4j database.

推荐答案

正如Andreas Ronge所说,使用Object.const_set时不会触发某些回调.评估字符串是可行的,所以这是我的解决方案:

As Andreas Ronge commented, some callbacks are not fired when using Object.const_set. Evaluating a string works, so this was my solution:

name ="Classname"
super_klass ="Neo4j::Rails::Model"
string_to_eval = "class #{name} < #{super_klass}; end;"
eval(string_to_eval, TOPLEVEL_BINDING)

这篇关于使用Object.const_set创建Rails模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆