Scaffolding 生成 Snippet
> rails g scaffold snippet caption:string content:text language:string section_id:integer
给 Snippet 的 Language 添加‘默认值’
db/migrate/2010..._create_snippets.rb
class CreateSnippets < ActiveRecord::Migration def change create_table :snippets do |t| t.string :caption t.text :content t.string :language, default: 'ruby' t.integer :section_id t.timestamps end endend
给 Snippet model 添加点东西
app/models/snippet.rb
class Snippet < ActiveRecord::Base belongs_to :section validates :caption, :presence => true validates :content, :presence => true def post_sequence section.post.sequence if section.post endend
同上,更改 Section Model
app/models/section.rb
class Section < ActiveRecord::Base ... has_one :snippet, :dependent => :destroy accepts_nested_attributes_for :snippet, :reject_if => lambda{ |a| a[:content].blank? && a[:caption].blank? } ...end
再同上,更改 Post Form
app/views/posts/_form.html.haml
...= simple_form_for(@post) do |f| = render 'shared/error_messages', :target => @post .inputs ... = f.simple_fields_for :sections do |section_f| .section ... = section_f.simple_fields_for :snippet do |snippet_f| .snippet %h3 Snippet = snippet_f.input :caption, :required => false = snippet_f.input :content, :input_html => {:rows =>5}, :required => false = snippet_f.input :language, :as => :select, :collection => coderay_languages %hr
添加代码高亮 Coderay
# Gemfilegem 'coderay'_________________# Terminal> bundle install
为 Coderay 书写 辅助方法
app/helpers/application_helper.rb
module ApplicationHelper def coderay(text, lang) CodeRay.scan(text, lang).div( :css => :class, :tab_width => 2) end def coderay_languages Hash[*CODERAY_LANGUAGES.map {|l| [l.humanize, l] }.flatten] endend
一些常量(Constants)
config/initializers/constants.rb
CODERAY_LANGUAGES = ["css", "html", "java_script", "json", "ruby", "sql", "xhtml", "yaml"]
改进我们的 Post controller (重构并加入新东西)
app/models/post.rb and app/controllers/posts_controller.rb
# post.rbclass Post < ActiveRecord::Base ... def build_section_and_snippet sections.build if sections.empty? sections.each{ |section| section.build_snippet if section.snippet.nil?} endend________________________________# posts_controller.rbclass PostsController < ApplicationController ... def new @post = Post.new(:sequence => Post.count + 1) @post.build_section_and_snippet end def edit @post = Post.find(params[:id]) @post.build_section_and_snippet endend
稍微调整 Post model
app/models/post.rb
class Post < ActiveRecord::Base ... accepts_nested_attributes_for :sections, :reject_if => proc { |attr| attr['heading'].blank? && attr['body'].blank? }