简体   繁体   中英

Multiple model.save's in 1 if condition with an unless

I'm trying to save a response and also save an issue if it's not nil in one condition so i don't have multiple if/else conditions complicating this logic.

For the use case where @response exists and issue is nil, this does not get into the if block.

Is there something obvious that i'm not seeing or can I not write my logic in one line like this?

Note: I know a transaction should be used, but i'm just trying to get a working prototype up right now.

  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

This is what I have working now and I was hoping there was an easier 1 liner rather than this.

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

You want to execute the "success" condition when:

  1. @response.save succeeded AND
  2. issue is nil OR issue is not nil and it saved successfully.

Thus, you can just do;

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

Since you are using && after @response.save , in case of issue.nil? the issue is not saved and returns a nil, which always causes it to give you a nil. I hope this will get you on the right track.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM