[英]How to refactor this Ruby on Rails code?
我想根據帖子的狀態來獲取帖子,因此我的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])
我會考慮將類方法添加到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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.