> rails g scaffold section heading:string body:text position:integer post_id:integer
> rake db:migrate
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
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 可以参考 Railscasts #196
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
app/controllers/post_controller.rb
def new
@post = Post.new(:sequence => Post.count + 1)
@post.sections.build
end
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