Define instance variables in controllers before any branching

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2021-05-15

My controller had the following code:

def create
  if captcha_wrong?
    render(action: redirection_action)
  else
    @seller = Seller.new(new_seller_params)
  end
end

And my view this:

<div id="law_seller_form">
  <%= semantic_form_for(@seller, :url => sellers_url) do |f| %>
  ...

When a bot submitted a form with no captcha, an error was thrown. This was because the @seller variable, expected in the view, was not available.

The fix is to define the instance variable first, before any branching happens.

def create
  @seller = Seller.new(new_seller_params)
  if captcha_wrong?
    render(action: redirection_action)
  else
    # default renders correctly
  end
end

Lesson

In controllers, define your instance variables before any branching occurs.