【发布时间】:2011-05-10 19:05:16
【问题描述】:
我经常在需要多种方法的地方构建控制器 (除了索引、编辑、显示等)。大多数时候我的动作 欲望可以归结为表演,因为它们是简单的 GET 操作, 但是我不想在任何一个控制器动作中加入太多逻辑。
以下是实现相同目的的两种不同方法的简单示例 东西……
class TwitterFriendController < ApplicationController
## lump everything into show?
def show
if params[:id] == "follow"
users = current_user.following
elsif params[:id] == "follow_me"
users = current_user.users_who_follow_me
elsif params[:id] == "following_follow_me"
users = current_user.following_who_follow_me
elsif params[:id] == "following_who_do_not_follow_me"
users = current_user.following_who_do_not_follow_me
...
end
respond_with do |format|
format.json do {...}
end
end
## or split everything out into separate methods, this requires
additional routing
def following
...
end
def users_who_follow_me
...
end
def following_who_follow_me
...
end
def following_who_do_not_follow_me
...
end
end
节目中的一切
- 一种方法中的大量逻辑
- 干燥? # 逻辑需要大量额外代码
- 减少路由
单独的方法
- 更多路由
- 不干燥
- 简单的方法查找
- 更易于阅读单个方法
所以真正的问题是,其中一种技术少 不好。
【问题讨论】:
标签: ruby-on-rails ruby controller