2010-06-02 82 views
0

我想根據他們的狀態獲取帖子,所以我的代碼在我的PostsControllerindex動作中。不過,這似乎是混亂的索引行動,我不確定它屬於這裏。如何重構這個Ruby on Rails代碼?

我怎樣才能讓它更簡潔,我在哪裏將它移動到我的應用程序中,以便它不會混亂我的索引操作(如果這是正確的操作)?

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
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,郵政.active.first,Post.active.each等

然後

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

我會考慮增加一個類的方法來發布

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 
+0

+1這就是我正在建議的 – 2010-06-02 22:04:49

+0

謝謝!我認爲你的意思是'def find_all_based_on_status status'而不是'def file_all_based_on_status status'。工作中的肌肉記憶。 另外,有沒有辦法讓查找代碼本身更簡潔? – 2010-06-02 22:07:03

+1

使你的finder方法使用@ zed_0xff的答案命名作用域 – 2010-06-02 22:14:09