1

我一直在 Rails 3 和 Mongoid 上做了一个高峰,并带着对 Grails 中自动脚手架的美好回忆,当我发现: http ://github.com/codez/dry_crud 时,我开始寻找 ruby​​ 的 DRY 视图

我创建了一个简单的类

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 回答