多个模型.save在1 if条件与除非



我试图保存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"条件:

  1. @response.save succeeded AND
  2. issuenil或者issue不是nil并且保存成功。

因此,您可以直接执行;

if @response.save and (issue.nil? or issue.save)
  # Success
else 
  # Fail
end

既然您在@response.save之后使用&&,万一出现问题。问题没有保存,并返回一个nil,这总是导致它给你一个nil。我希望这能让你走上正确的道路。

最新更新