1

我在控制器中有一个动作,如下所示:

  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。有没有更好的方法来编写这个动作?

4

2 回答 2

3

我会这样写

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
于 2012-09-07T09:47:48.717 回答
1

也许你可以用这样的东西重构你的项目模型

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
于 2012-09-07T09:57:00.620 回答