我试图保存response
,也保存issue
,如果它不是nil
在一个条件下,所以我没有多个if/else条件使这个逻辑复杂化。
对于@response
存在且issue
为nil的用例,这不会进入if块。
是否有一些明显的东西我没有看到,或者我可以不写我的逻辑在一行像这样?
注意:我知道应该使用事务,但我现在只是想得到一个工作原型。
if @response.save && (issue.save unless issue.nil?) # Does not get into the if block when @response exists and issue is nil
p 'in save'
format.html { redirect_to issue_path(params[:issue_id]), notice: success_message }
else
p 'not in save'
format.html { render action: 'new' }
end
这是我现在正在工作的,我希望有一个更简单的1 liner而不是这个。
success = false
if issue.nil?
if @response.save
success = true
end
else
if @response.save && issue.save
success = true
end
end
if success
p 'in save'
format.html { redirect_to issue_path(params[:issue_id]), notice: success_message }
else
p 'not in save'
format.html { render action: 'new' }
end
在以下情况下执行"success"条件:
-
@response.save
succeeded AND -
issue
是nil
或者issue
不是nil
并且保存成功。
因此,您可以直接执行;
if @response.save and (issue.nil? or issue.save)
# Success
else
# Fail
end
既然您在@response.save
之后使用&&
,万一出现问题。问题没有保存,并返回一个nil,这总是导致它给你一个nil。我希望这能让你走上正确的道路。