【译】把模型的逻辑移到模型中

Saturday, July 24, 2010

原文:http://rails-bestpractices.com/posts/7-move-model-logic-into-the-model

在MVC中, 控制器应该尽量简单,处理业务逻辑是模型的职责,所以我们需要把逻辑代码从控制器中移到模型中来

丑陋的...

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

在这个例子中, 在控制器中想发布一篇文章, 首先要找到一篇文章,
设置文章的属性is_published为真和approved为当前用户,根据创建时间来设置popular属性,这样的话控制器知道了太多的逻辑,
这不是控制器的职责, 应该由模型来处理。

重构...

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

现在我们把发布逻辑从控制器移到了模型中来了, 在模型中定义一个发布方法, 然后在控制器中调用它, 这样看起来多漂亮呀

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top