祖先和rails_admin,下拉列表

时间:2011-11-12 23:52:25

标签: ruby-on-rails rails-admin

我正在尝试Rails_Admin。对于一组文章,我正在使用祖先。因此,我想在新的和编辑页面中创建一个下拉列表,这使我能够选择正确的父文章。

我当前的配置:

  config.model Article do
  #   # Found associations:

    # Found columns:
      field :id, :integer 
      field :title, :string 
      field :description, :text 
      field :content, :text do
        ckeditor true
      end
      #field :created_at, :datetime 
      #field :updated_at, :datetime 
      field :ancestry, :enum do
        @articles = Article.scoped
        @articles.arrange(:order => :created_at)
      end
    # Sections:
    list do; end
    export do; end
    show do; end
    edit do; end
    create do; end
    update do; end
  end

所以,非常标准,除了:enum字段。我一定是在做错事。有什么想法吗?

我已经看过了How to arrange entries from Ancestry tree in dropdown list in Rails 3?,但除非我误解了他们正在做的一些问题。我想使用编配功能。

5 个答案:

答案 0 :(得分:5)

我用rails_admin编写了这个插件来管理祖先:rails_admin_nestable 我希望会有用。 enter image description here

答案 1 :(得分:1)

实现目标的最简单方法是

在你的模特中:

class Article < ActiveRecord::Base
  has_ancestry
  attr_accessor :parent_id
  #...
end

接下来将正确的字段添加到config.model

field :parent_id, :enum do
  enum do
    Article.select(:id).map{|article| article.id} #this is just an example though
  end
end

答案 2 :(得分:1)

按如下方式在rails_admin中配置模型:

  config.model Article do
    list do
      field :title
      field :parent do
        formatted_value do
          value.title if value
        end
      end
    end

    show do
      field :title
      field :parent do
        formatted_value do
          value.title if value
        end
      end
    end

    edit do
      field :title
      field :ancestry, :enum do
        enum do
          except = bindings[:object].id
          Article.where("id != ?", except).map { |c| [ c.title, c.id ] }
        end
      end
    end
  end

答案 3 :(得分:0)

实际上对我来说解决方案是:

before_validation :check_ancestry

def check_ancestry
  if self.ancestry.blank?
    self.ancestry=nil
  end
end

def percorso
  p=""
  self.ancestors.each do |n|
    p+=n.title + " -> "
  end
  p+=self.title
end

rails_admin do
  edit do
    field :ancestry, :enum do
      enum do
        except = bindings[:object].id.nil? ? 0 : bindings[:object].id
        Article.where("id != ?", except).map { |c| [ c.percorso, c.ancestry? ? "#{c.ancestry}/#{c.id}":"#{c.id}" ]}
      end
    end
  end
end

答案 4 :(得分:0)

我把它放在我的config/initializers/rails_admin.rb

    config.model 'MyModel' do
      edit do
        include_all_fields
        field :parent_id, :enum do
          enum do
            MyModel.all.map{|model| [model.name, model.id ]}.to_a
          end
        end
       exclude_fields :ancestry
      end
    end