Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails/SaveBang does not work with instance variables #1228

Open
markokajzer opened this issue Jan 4, 2024 · 1 comment
Open

Rails/SaveBang does not work with instance variables #1228

markokajzer opened this issue Jan 4, 2024 · 1 comment

Comments

@markokajzer
Copy link
Contributor

markokajzer commented Jan 4, 2024

Expected behavior

Local variable

@user = User.create(create_params)
if @user.persisted?
  do_work
end

and instance variable

user = User.create(create_params)
if user.persisted?
  do_work
end

behave the same.

Actual behavior

They do not 馃憞

Local variable

class UsersController < ApplicationController
  def create
    user = User.create(create_params)

    if user.persisted?
      redirect_to root_path
    else
      redirect_to other_path
    end
  end
end
Inspecting 1 file
.

1 file inspected, no offenses detected

Instance variable

class UsersController < ApplicationController
  def create
    @user = User.create(create_params)

    if @user.persisted?
      redirect_to root_path
    else
      redirect_to other_path
    end
  end
end
Inspecting 1 file
C

Offenses:

app/controllers/users_controller.rb:3:18: C: [Correctable] Rails/SaveBang: Use create! instead of create if the return value is not checked.
    @user = User.create(create_params)
                 ^^^^^^

Steps to reproduce the problem

See above.

RuboCop version

$ [bundle exec] rubocop -V
1.59.0 (using Parser 3.2.2.4, rubocop-ast 1.30.0, running on ruby 3.2.0) [arm64-darwin21]
  - rubocop-rails 2.23.1
@markokajzer
Copy link
Contributor Author

Seems like one can workaround this issue by using .new + #save instead of .create + .persisted? 馃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant