0
我想根據他們的狀態獲取帖子,所以我的代碼在我的PostsController
index
動作中。不過,這似乎是混亂的索引行動,我不確定它屬於這裏。如何重構這個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])
+1這就是我正在建議的 – 2010-06-02 22:04:49
謝謝!我認爲你的意思是'def find_all_based_on_status status'而不是'def file_all_based_on_status status'。工作中的肌肉記憶。 另外,有沒有辦法讓查找代碼本身更簡潔? – 2010-06-02 22:07:03
使你的finder方法使用@ zed_0xff的答案命名作用域 – 2010-06-02 22:14:09