2012-04-13 9 views
0

にStruct.newを()を使用して:問題私は、次のようなmongoidモデルと方法をしたのRails 3.2.3 MongoIDモデル法

class Category 
    include Mongoid::Document 
    field :name, :type => String 
    ... 

    def self.custom_find 
    ... 
    Str = Struct.new(:arg1, :arg2) 
    array << Str.new(one, two) 
    ... 
    end 
end 

と私は次のエラーを取得する:

dynamic constant assignment (SyntaxError) 
    Str = Struct.new(:arg1, :arg2) 

私は設定/初期化子/ categories.rbにStr = Struct.new(:arg1, :arg2)を移動しようとしたが、その後、私は得る:

BSON::InvalidDocument in TrendsController#index 

Cannot serialize an object of class Category into BSON. 

除去することにより、 custom_find違反メソッドは、他のeverithingうまく動作し、私は何かが"Struct"に関連していると思います。

+1

Structは、Rubyで明示的なクラスを記述することなく、アクセサメソッドを使用して複数の属性をまとめてバンドルする便利な方法です(http://www.ruby-doc.org/core-1.9.3/Struct .html) –

+0

これはすでに見つかりました。コメントする前にグーグルする必要があります:) –

答えて

2

あなたはいくつかの方法でダイナミックな一定の割り付けエラーを回避することができます。

array = Struct.new(:arg1, :arg2).new(one, two) 

または

Object.const_set :Str, Struct.new(:arg1, :arg2) 
Str # => Str 

はこのしかし、シリアル化の問題を解決するべきではありません。

+0

...私はObject.const_set、ありがとう! –

関連する問題