【译】让finder存在于所属的模型中

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/13-keep-finders-on-their-own-model

根据解耦(Decoupling)原理, 模型应该处理自己的finder,一个模型不必要知道关于关联模型的finder逻辑

丑陋的...

class Post < ActiveRecord::Base
  has_many :comments

def find_valid_comments
    self.comment.find(:all, :conditions => {:is_spam => false},
                :limit => 10)
  end
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

class CommentsController < ApplicationController
  def index
    @comments = @post.find_valid_comments
  end
end

在这个例子中, 文章模型负责了处理复杂的评论finder, 但是不是它的工作, 我们应该把有效评论的finder(valid comments
finder) 移到评论模型中去

重构...

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post

named_scope :only_valid, :conditions => { :is_spam => false }
  named_scope :limit, lambda { |size| { :limit => size } }
end

class CommentsController < ApplicationController
  def index
    @comments = @post.comments.only_valid.limit(10)
  end
end

我们用named_scope的方式把有效评论的finder(valid comments finder) 移到评论模型中来了,
这样文章模型和评论模型就更松耦合更容易扩展。

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