我在控制器中有一个操作,看起来像这样:
def show
@project = current_customer.projects.where(id: params[:project_id]).first
if @project
@feature = @project.features.where(id: params[:feature_id]).first
if @feature
@conversation = @feature.conversations.where(id: params[:id]).first
unless @conversation
head 401
end
else
head 401
end
else
head 401
end
end
问题是head 401
的重复。有没有更好的方法来写这个动作?
我会这样写
def show
@project = current_customer.projects.where(id: params[:project_id]).first
@feature = @project.features.where(id: params[:feature_id]).first if @project
@conversation = @feature.conversations.where(id: params[:id]).first if @feature
# error managment
head 401 unless @conversation
end
也许你可以用这样的来重构你的项目模型
Model Project
...
def get_conversation
feature = features.where(id: params[:feature_id]).first
conversation = feature.conversations.where(id: params[:id]).first if feature
end
在你的控制器
Controller ProjectController
def show
@project = current_customer.projects.where(id: params[:project_id]).first
@conversation = @project.get_conversation
head 401 unless @conversation
end