使用带有rails 3和dry_crud的Mongoid时替换column_names

我一直在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并且上面的类不inheritance自ActiveRecord :: Base,我必须为column_names创建我自己的实现,如上所述。 我想知道是否可以创建一个默认实现,返回上面的所有字段,而不是硬编码列表?

如果没有在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 

现在你的模型可以从该类inheritance而不是包含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 

当你有一个内置的方法时,为什么要经历这样做的麻烦呢?

对于Mongoid:

 Model.attribute_names # => ["_id", "created_at", "updated_at", "species", "captured_by", "weight", "length"]