Skip to content

Move Model Logic into the Model

Richard Huang edited this page Aug 15, 2010 · 3 revisions

Please go to http://rails-bestpractices.com/posts/7-move-model-logic-into-the-model

Before:


class PostsController < ApplicationController

  def publish
    @post = Post.find(params[:id])
    @post.update_attribute(:is_published, true)
    @post.approved_by = current_user
    if @post.created_at > Time.now - 7.days
      @post.popular = 100
    else
      @post.popular = 0
    end

    redirect_to post_url(@post)
  end

end

After:


class Post < ActiveRecord::Base

  def publish
    self.is_published = true
    self.approved_by = current_user
    if self.created_at > Time.now - 7.days
      self.popular = 100
    else
      self.popular = 0
    end
  end

end

class PostsController < ApplicationController

  def publish
    @post = Post.find(params[:id])
    @post.publish

    redirect_to post_url(@post)
  end

end