Reputation: 2076
I have an action in a controller that looks like this:
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
The problem is the repetition of head 401
. Is there a better way to write this action ?
Upvotes: 1
Views: 100
Reputation: 111
Maybe you can refactor in your project model with something like this
Model Project
...
def get_conversation
feature = features.where(id: params[:feature_id]).first
conversation = feature.conversations.where(id: params[:id]).first if feature
end
And in your Controller
Controller ProjectController
def show
@project = current_customer.projects.where(id: params[:project_id]).first
@conversation = @project.get_conversation
head 401 unless @conversation
end
Upvotes: 1
Reputation: 24340
I would write it like this
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
Upvotes: 3