Skip to content
Richard Huang edited this page Aug 15, 2010 · 2 revisions

Please go to: http://rails-bestpractices.com/posts/5-use-model-callback

Before:


<% form_for @post do |f| %>
  <%= f.text_field :content %>
  <%= check_box_tag 'auto_tagging' %>
<% end %>

class PostsController < ApplicationController

  def create
    @post = Post.new(params[:post])

    if params[:auto_tagging] == '1'
      @post.tags = AsiaSearch.generate_tags(@post.content)
    else
      @post.tags = ""
    end

    @post.save
  end

end

After:


class Post < ActiveRecord::Base

  attr_accessor :auto_tagging
  before_save :generate_tagging

  private

  def generate_taggings
    return unless auto_tagging == '1'
    self.tags = Asia.search(self.content)
  end

end

<% form_for @post do |f| %>
  <%= f.text_field :content %>
  <%= f.check_box :auto_tagging %>
<% end %>

class PostsController < ApplicationController

  def create
    @post = Post.new(params[:post])
    @post.save
  end

end