代码之家  ›  专栏  ›  技术社区  ›  Yuval Karmi

如何重构这个RubyonRails代码?

  •  0
  • Yuval Karmi  · 技术社区  · 14 年前

    我想根据职位的状态获取职位,所以我在我的 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 回复  |  直到 14 年前
        1
  •  2
  •   zed_0xff    14 年前
    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
    
        2
  •  2
  •   GSP    14 年前

    我会考虑在post中添加一个类方法

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

    这样你的控制器索引就简单了

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