ruby on rails

My Page model look like this:

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 model look like this:

class Block < ActiveRecord::Base
  belongs_to :page

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

I needed workflow like this: As an admin I click create page and I should see opened new block section with prefield title.

在这里输入图像描述

How can I create this scenario?


我自己的回答实际上是有礼貌的,但它适用于我:

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
链接地址: http://www.djcxy.com/p/67056.html

上一篇: 红宝石在轨道上

下一篇: 红宝石在轨道上