1

Rails 3とMongoidでスパイクを実行していて、Grailsでの自動足場の楽しい思い出とともに、次の場所を見つけたときにRubyのDRYビューを探し始めました:http: //github.com/codez/dry_crud

簡単なクラスを作成しました

class Capture 
  include Mongoid::Document
  field :species, :type => String
  field :captured_by, :type => String
  field :weight, :type => Integer
  field :length, :type => Integer

  def label
      "#{name} #{title}"
  end

  def self.column_names
    ['species', 'captured_by', 'weight', 'length']  
  end
end

ただし、dry_crudはself.column_namesに依存し、上記のクラスはActiveRecord :: Baseを継承しないため、上記のようなcolumn_namesの独自の実装を作成する必要があります。ハードコードされたリストの代わりに、上記のすべてのフィールドを返すデフォルトの実装を作成できるかどうか知りたいですか?

4

2 に答える 2

4

組み込みのメソッドがあるのに、なぜそれをすべて行うのに苦労するのでしょうか。

Mongoidの場合:

Model.attribute_names
# => ["_id", "created_at", "updated_at", "species", "captured_by", "weight", "length"] 
于 2014-07-16T22:46:25.670 に答える
3

Mongoid :: Documentに新しいメソッドを挿入する以外に、モデルでこれを行うことができます。

self.fields.collect { |field| field[0] }

更新:あなたが冒険に落ちたなら、うーん、まだ良いです。

モデルフォルダに新しいファイルを作成し、model.rbという名前を付けます

class Model
  include Mongoid::Document
  def self.column_names
    self.fields.collect { |field| field[0] }
  end
end

これで、モデルはMongoid :: Documentを含める代わりに、そのクラスから継承できます。Capture.rbは次のようになります

class Capture < Model
  field :species, :type => String
  field :captured_by, :type => String
  field :weight, :type => Integer
  field :length, :type => Integer

  def label
      "#{name} #{title}"
  end
end

これで、これを任意のモデルにネイティブに使用できます。

Capture.column_names
于 2010-09-08T20:37:38.190 に答える