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

ruby, ruby-on-rails, ruby-on-rails-4

Solution

You want to execute the "success" condition when:

- `@response.save` succeeded AND

- `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

Problem

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 ```

Original source