如何重构这个Ruby on Rails代码?

时间:2010-06-02 21:55:25

标签: ruby-on-rails refactoring dry

我想根据其状态获取帖子,因此我在PostsController index操作中包含此代码。但是,这似乎使索引行动变得混乱,我不确定它属于这里。

我怎样才能使它更简洁,我在应用程序中将它移动到哪里,这样就不会使我的索引操作变得混乱(如果这是正确的事情)?

if params[:status].empty?
  status = 'active'
else
  status = ['active', 'deleted', 'commented'].include?(params[:status]) ? params[:status] : 'active'
end

case status
when 'active'
  #active posts are not marked as deleted and have no comments
  is_deleted = false
  comments_count_sign = "="
when 'deleted'
  #deleted posts are marked as deleted and have no comments
  is_deleted = true
  comments_count_sign = "="
when 'commented'
  #commented posts are not marked as deleted and do have comments
  is_deleted = false
  comments_count_sign = ">"
end

@posts = Post.find(:all, :conditions => ["is_deleted = ? and comments_count_sign #{comments_count_sign} 0", is_deleted])

2 个答案:

答案 0 :(得分:2)

我会考虑在Post

中添加一个类方法
def file_all_based_on_status status

  # custom logic for queries based on the given status here
  # handling nils and other cases

end

那样你的Controller索引很简单

def index
  @posts = Post.find_all_based_on_status params[:status]
end

答案 1 :(得分:2)

class Post < ActiveRecord::Base
  named_scope :active, :conditions => { :is_deleted => false, :emails_count => 0 }
  named_scope :sent, :conditions => ["is_deleted = ? AND emails_count > 0", true]
  ...
end

像Post.active.all,Post.active.first,Post.active.each等一样使用它

然后

status = %w'active deleted sent'.include?(params[:status]) : params[:status] : 'active'
@posts = Post.send(status).all