下面的操作会创建一条新评论。Rails:如何优化此操作
- 用户有很多状态
- 一个状态有很多评论
使head 401 and return
不重复多少次能优化这个动作。
def create
@user = User.where(id: params[:user_id]).first
if @user
if current_user.friend_with?(@user) or current_user == @user
@status = @user.statuses.where(id: params[:status_id]).first
if @status
@comment = @status.comments.build(params[:comment])
@comment.owner = current_user
if @comment.valid?
@comment.save
current_user.create_activity(:comment_status, @comment, @user)
else
head 401 and return
end
else
head 401 and return
end
else
head 401 and return
end
else
head 401 and return
end
end
谢谢。
'那里(:ID => ...)。first'并不完全等同于'find',因为'find'引发'的ActiveRecord :: RecordNotFound'而不是返回零。这种情况现在将返回404,而不是标准错误页面而不是401。此外,'head 401和return'将返回401没有内容,而'render(status:401)'将呈现401状态的模板。 – willglynn
你能解释一下为什么你建议不使用内容而不使用'head'使用'render'? – shime
@shime因为简单地'返回'意味着渲染没有内容是一个副作用,而不是一个明确的陈述。最好先说明你的意图,而不是依赖副作用,读者期待他们。 –