Scaffolding 生成 section
> rails g scaffold section heading:string body:text position:integer post_id:integer> rake db:migrate
## 给 section model 添点料 app/models/section.rb
class Section < ActiveRecord::Base default_scope order("position ASC") belongs_to :post validates :heading, :presence => true validates :body, :presence => true validates :position, :presence => true, :numericality => { :greater_than => 0}end
给 post model 添点料
app/models/post.rb
class Post < ActiveRecord::Base... has_many :sections, :dependent => :destroy accepts_nested_attributes_for :sections, :reject_if => :all_blank...end
accepts_nested_attributes_for 可以参考
将 post 表单改为 嵌套(Nested) 表单
app/views/posts/_form.html.haml
= simple_form_for @post do |f|... = f.simple_fields_for :sections do |section_f| .section %h2 Section = section_f.input :heading = section_f.input :body, :input_html => {:rows =>5} = section_f.input :position = f.button :submit
修改 Posts Controller 的 new 方法
app/controllers/post_controller.rb
def new @post = Post.new(:sequence => Post.count + 1) @post.sections.buildend
更改 Post 的 Show 页面
app/views/posts/show.html.haml
%h1= "\##{@post.sequence} #{@post.title}"%p= sanitize @post.description- for section in @post.sections .section %h2= section.heading .body= sanitize section.body %hr