Replacement for column_names when using Mongoid with rails 3 and dry_crud

倾然丶 夕夏残阳落幕 提交于 2020-01-05 07:52:07

问题


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?


回答1:


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



回答2:


Why would you go through the trouble of doing all that when there's an in-built method?

For Mongoid:

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


来源:https://stackoverflow.com/questions/3669991/replacement-for-column-names-when-using-mongoid-with-rails-3-and-dry-crud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!