rails_admin - has_many association - 默认值

时间:2014-03-07 11:35:20

标签: ruby-on-rails rails-admin

我的网页模型如下所示:

class Page < ActiveRecord::Base
  has_many :blocks

  accepts_nested_attributes_for :blocks, allow_destroy: true

  rails_admin do
    edit do
      fields :title, :slug, :blocks
    end
  end
end

My Block模型如下所示:

class Block < ActiveRecord::Base
  belongs_to :page

  rails_admin do
    edit do
      field :title
      field :body, :ck_editor
    end
  end
end

我需要这样的工作流程: 作为管理员,我点击创建页面,我应该看到打开的新区块部分与prefield标题。

enter image description here

如何创建此方案?

1 个答案:

答案 0 :(得分:2)

我自己的答案真的很脏,但它对我有用:

class Page < ActiveRecord::Base
  has_many :blocks

  accepts_nested_attributes_for :blocks, allow_destroy: true

  rails_admin do
    edit do
      fields :title, :slug
      field :blocks do
        # It is needed to show nested form
        active true
      end
    end
  end

  # It is needed to create default block with title "main"
  after_initialize do
    if self.blocks.empty? && self.new_record?
      self.blocks << Block.new(title: 'main')
    end
  end

  # It is needed to prevent create default block when form has errors
  after_validation do
    return if(self.persisted? || self.blocks.empty?)
    destroy_array = []
    self.blocks.each do |block|
      destroy_array << block if block.title == 'main' && block.body.nil?
    end
    self.blocks.destroy(destroy_array)
  end
end