Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does rails generate object instance variables in controllers

Why does rails use @poop object instance variables instead of just a local poop variable in the generated code? Is there some foreseen common situation where it's useful rather than simply using a local variable here? I would think it makes sense to use a local variable and not attach something to the object namespace unless you need it there.

  # GET /poop/1
  # GET /poop/1.xml
  def show
    @poop = Poop.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @poop }
    end
  end
like image 277
emery Avatar asked Jan 25 '26 11:01

emery


2 Answers

Is there some foreseen common situation where it's useful rather than simply using a local variable here?

Of course there is. The default situation is like that. Check the source code of auto-generated (with use of script/generate/scaffold) view in app/views/poops/show.html.erb:

<p>
  <b>Field:</b>
  <%=h @poop.field %>
</p>
<%= link_to 'Edit', edit_poop_path(@poop) %>

If the variable was local to the controller method, how would the renderer access the element you found with find(params[:id])? respond_to doesn't directly call the component that renders the page. Instead, it delays its execution up to the point when local variables would already be out of scope. Then the only way renderer could communicate to what was calculated in the controller is with use of instance variables.

like image 63
P Shved Avatar answered Jan 28 '26 00:01

P Shved


It is idiomatic to use controller instance variables when you need to make those values available in the associated views and helpers. Otherwise the use of locally scoped variables in controller logic is probably preferable.

That said, if you find that your controllers are using a lot of variables (indicative of complexity) then best-practice would suggest that you move that logic into the models, keeping the controllers lean.

like image 33
bjg Avatar answered Jan 28 '26 00:01

bjg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!