代码之家  ›  专栏  ›  技术社区  ›  orjan

在使用MongoID和Rails 3和Dry_Crud时替换列名称

  •  1
  • orjan  · 技术社区  · 14 年前

    我在Rails3和Mongoid上做了一个Spike,在Grails的自动脚手架的美好记忆中,我开始寻找Ruby的干燥视图,当我发现: 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_名称,并且上面的类不是从activeRecord::base继承的,因此我必须为上面的列_名称创建自己的实现。我想知道是否可以创建一个返回上面所有字段而不是硬编码列表的默认实现?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Hugo    14 年前

    除了在mongoid::document中注入新方法之外,您可以在模型中这样做。

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

    更新 如果你喜欢冒险,那就更好了。

    在model文件夹中创建一个新文件并将其命名为model.rb

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

    现在,您的模型可以从该类继承,而不是包含mongoid::document。 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
    
        2
  •  4
  •   Sheharyar    7 年前

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

    Mongoid:

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