raj
raj

Reputation: 6094

redirect_to root_url and return unless @user.activated

This is my users_controller method. it should be redirected if user is not activated.

def show
  @user = User.find(params[:id])
  redirect_to root_url and return unless @user.activated?
end

Here I dont understand the need of return in the method as it would happen automatically before the redirect_to is executed. I have seen many example but most of them have more if statements, so return skips those checks. Here, is it necessary?

Upvotes: 3

Views: 1933

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176412

The return statement makes no sense here. You can just write

def show
  @user = User.find(params[:id])
  redirect_to(root_url) unless @user.activated?
end

The return statement is sometimes uses as a trick to avoid the double rendering issue, especially with explicit render. Take this example:

def show
  @user = User.find(params[:id])
  redirect_to(some_url) unless @user.activated?
  redirect_to(other_url) unless @user.other?
  render action: "hello"
end

If you don't use the return here, when the method returns there is a chance that you defined a rendering behavior twice or even three times.

Generally speaking, multiple rendering with returns is a sign of coding smell. You can often refactor the action to properly use before actions that are designed to stop the execution chain if any of the action set a rendering behavior.

Upvotes: 2

If You use Devise, You could write:

  # GET /users/:id.:format
  def show
    # authorize! :read, @user
  end

It is workable as default.

Update. Pay attention: If You have to enable activation via email, You could write:

In device.rb (find this strings and uncomment it):

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming his account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming his account,
  # access will be blocked just in the third day. Default is 0.days, meaning
  # the user cannot access the website without confirming his account.
  config.confirm_within = 2.days

  # Defines which key will be used when confirming an account
  config.confirmation_keys = [ :email ]

And in User Model (add into device string):

device ..., :comfirmable

Upvotes: -1

Related Questions