views:

52

answers:

1

I've been doing a spike on Rails 3 and Mongoid and with the pleasant memories of the auto scaffolding in Grails I started to look for a DRY view for ruby when I found: http://github.com/codez/dry_crud

I created a simple class

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

But since dry_crud depends on self.column_names and the class above doesn't inherit from ActiveRecord::Base I have to create my own implementation for column_names like the one above. I would like to know if it possible to create a default implementation returning all of the fields above, instead of the hard coded list?

A: 

Short of injecting a new method in Mongoid::Document you can do this in your model.

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

Update : Uhm better yet, if you fell adventurous.

In the model folder make a new file and name it model.rb

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

Now your model can inherit from that class instead of include Mongoid::Document. capture.rb will look like this

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

Now you can use this natively for any model.

Capture.column_names
Hugo
I might try using that myself actually.
Hugo
Works like a charm but dry_crud won't work as soon as I add a references_one :species
orjan