Skip to content

Move Model Logic into the Model

flyerhzm edited this page Aug 13, 2010 · 3 revisions

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